package com.zmn.oms.zmn.business.impl.work.orderpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.google.api.client.util.Sets;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.account.dubbo.interfaces.account.AccountListRemoteService;
import com.zmn.base.common.data.common.constant.TagConsts;
import com.zmn.base.common.data.common.dro.tags.TagsDRO;
import com.zmn.base.common.data.common.query.tags.TagsQuery;
import com.zmn.base.common.data.dubbo.interfaces.tags.TagsListRemoteService;
import com.zmn.base.shortlink.common.constant.DubboConsts;
import com.zmn.base.shortlink.common.dio.wechat.WeChatTemporaryQRCodeDIO;
import com.zmn.base.shortlink.common.dro.wechat.temporary.WeChatTemporaryQRCodeDRO;
import com.zmn.base.shortlink.dubbo.interfaces.wechat.WechatTemporaryQrcodeModifyRemoteService;
import com.zmn.cds.httpcall.CdsHttpCallClient;
import com.zmn.cds.httpcall.CdsHttpCallResult;
import com.zmn.cds.httpcall.biz.paylink.ApplyPayLinkDIO;
import com.zmn.cds.httpcall.biz.paylink.ApplyPayLinkDRO;
import com.zmn.common.constant.FicoConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.amount.AmountUtil;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.http.HttpUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.dms.common.enums.DiscountTypeEnums;
import com.zmn.dms.dubbo.interfaces.coup.coupon.CoupOnceCardRemoteService;
import com.zmn.manager.mq.constant.MqTopicConsts;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.business.interfaces.conf.channel.ConfOrderChannelBService;
import com.zmn.oms.business.interfaces.log.OrderLogMessageBService;
import com.zmn.oms.business.interfaces.messageV1.app.MessageSendAppService;
import com.zmn.oms.business.interfaces.messageV1.common.MessageGetSendInfoService;
import com.zmn.oms.business.interfaces.work.masterwork.MasterWorkBService;
import com.zmn.oms.business.interfaces.work.orderpay.FactoryAccountModifyBService;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dro.PayChannelDRO;
import com.zmn.oms.common.dro.conf.channel.ConfOrderChannelDRO;
import com.zmn.oms.common.dro.orderpay.OrderPayResultDRO;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.common.dto.OmsPayRequestDTO;
import com.zmn.oms.common.dto.OmsRefundRequestDTO;
import com.zmn.oms.common.enums.RefundInitiateTypeEnum;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.ProductInfoUtil;
import com.zmn.oms.manager.utils.OmsMqTagConsts;
import com.zmn.oms.manager.utils.SpringBeanFactoryUtil;
import com.zmn.oms.model.bo.refund.RefundInitiateBO;
import com.zmn.oms.model.dro.refund.RefundBacktrackingAmountDRO;
import com.zmn.oms.model.dto.work.masterwork.CompleteDTO;
import com.zmn.oms.model.dto.work.modify.must.ZsOrderPayDTO;
import com.zmn.oms.model.dto.work.refund.RefundDTO;
import com.zmn.oms.model.entity.chan.pay.AbnormalPayment;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.log.OrderMessageLog;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.orderappbind.OrderThirdAppBind;
import com.zmn.oms.model.entity.pay.OrderPay;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.chan.pay.AbnormalPaymentService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.invoice.OrderInvoiceService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.pay.OrderPayService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.shop.OrderShopService;
import com.zmn.oms.services.interfaces.work.OrderWorkAmountService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.daowei.DaoweiConsts;
import com.zmn.oms.third.daowei.service.DaoweiService;
import com.zmn.oms.third.dj58.DaoJia58Consts;
import com.zmn.oms.third.dj58.service.DaoJia58Service;
import com.zmn.oms.third.gomegj.service.GmgjService;
import com.zmn.oms.third.tc58.Tc58Consts;
import com.zmn.oms.third.tc58.service.Tc58Service;
import com.zmn.oms.third.yajule.service.YajuleService;
import com.zmn.oms.zmn.business.interfaces.orderpay.OrderPayChannelBService;
import com.zmn.oms.zmn.business.interfaces.pay.OrderPayBService;
import com.zmn.oms.zmn.business.interfaces.work.masterwork.ZsMasterWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.orderpay.ZsOrderPayBService;
import com.zmn.oms.zmn.normal.business.interfaces.refund.RefundBService;
import com.zmn.pay.common.constant.PayAmountTypeConsts;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.pay.gateway.common.constants.OrderTypeConsts;
import com.zmn.pay.gateway.common.enums.AppEnum;
import com.zmn.pay.gateway.common.model.dio.PayGatewayDIO;
import com.zmn.pay.gateway.common.model.dio.RefundGatewayDIO;
import com.zmn.pay.gateway.common.model.dio.pay.*;
import com.zmn.pay.gateway.common.model.dro.PayGatewayDRO;
import com.zmn.pay.gateway.common.model.dro.PayOrderDRO;
import com.zmn.pay.gateway.common.model.dro.RefundDRO;
import com.zmn.pay.gateway.common.model.dro.RefundResultDRO;
import com.zmn.pay.gateway.dubbo.interfaces.pay.PayGatewayRemoteService;
import com.zmn.pay.gateway.dubbo.interfaces.refund.RefundRemoteService;
import com.zmn.pay.gateway.dubbo.interfaces.trade.RechargeModifyRemoteService;
import com.zmn.saas.dubbo.constant.SaasDubboConsts;
import com.zmn.saas.dubbo.interfaces.app.AppRemoteService;
import com.zmn.vas.common.consts.VasPayConsts;
import com.zmn.vas.common.dio.order.card.times.RefundTimesCardDIO;
import com.zmn.vas.common.dro.order.card.times.RefundTimesCardDRO;
import com.zmn.vas.dubbo.consts.VasDubboConsts;
import com.zmn.vas.dubbo.interfaces.order.card.times.VasOrderTimesCardModifyRemoteService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：啄木鸟工单支付
 *
 * @author heciqi
 * @date 2019/01/08 20:14
 */
@Slf4j
@Service
public class ZsOrderPayBServiceImpl implements ZsOrderPayBService {

	@Autowired
	private OrderWorkService orderWorkService;
	@Autowired
	private OrderDetailService orderDetailService;
	@Autowired
	private OrderDiscountService orderDiscountService;
	@Autowired
	private OrderWorkAmountService orderWorkAmountService;
	@Autowired
	private ZsMasterWorkBService zsMasterWorkBService;
    @Autowired
    private OrderMasterService orderMasterService;
	@Autowired
	private OrderInvoiceService orderInvoiceService;
	@Autowired
	private DaoJia58Service daoJia58Service;
	@Autowired
	private YajuleService yajuleService;
	@Autowired
	private GmgjService gmgjService;
	@Autowired
	private OrderShopService orderShopService;
	@Autowired
	private OrderServiceItemService orderServiceItemService;
	@Autowired
	private Tc58Service tc58Service;
	@Autowired
	private DaoweiService daoweiService;
	@Autowired
	private AbnormalPaymentService abnormalPaymentService;
	@Autowired
	private RedisManager redisManager;
	@Autowired
	private MessageGetSendInfoService messageGetSendInfoService;
    @Autowired
    private OrderLogMessageBService orderLogMessageBService;
	@Autowired
	private MasterWorkBService masterWorkBService;
	@Autowired
	private OrderPayChannelBService orderPayChannelBService;
	@Autowired
	private OrderPayBService orderPayBService;
	@Autowired
	private OrderPayService orderPayService;
	@Autowired
	private RefundBService refundBService;
	@Autowired
	MessageSendAppService messageSendAppService;
	@Autowired
	private OrderExtendService orderExtendService;

	@Autowired
	private FactoryAccountModifyBService factoryAccountModifyBService;
	@Reference(version = com.zmn.pay.gateway.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
	private PayGatewayRemoteService payGatewayRemoteService;
	@Reference(version = com.zmn.pay.gateway.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
	private RefundRemoteService refundRemoteService;
	@Reference(version = com.zmn.pay.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
	private RechargeModifyRemoteService rechargeModifyRemoteService;
	@Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
	private WechatTemporaryQrcodeModifyRemoteService wechatTemporaryQrcodeModifyRemoteService;
	@Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
	private TagsListRemoteService tagsListRemoteService;
	@Reference(version = com.zmn.account.dubbo.utils.AccountDubboConsts.INTERFACE_VERSION, check = false)
	private AccountListRemoteService accountListRemoteService;
	@Reference(version = SaasDubboConsts.INTERFACE_VERSION, check = false)
	private AppRemoteService appRemoteService;
	@Reference(version = VasDubboConsts.INTERFACE_VERSION, check = false)
	private VasOrderTimesCardModifyRemoteService vasOrderTimesCardModifyRemoteService;
	@Reference(version = VasDubboConsts.INTERFACE_VERSION, check = false)
	private CoupOnceCardRemoteService coupOnceCardRemoteService;

	@Resource
    private ConfOrderChannelBService confOrderChannelBService;

	@Value("${wechat.qrcode.url:http://app.xiujiadian.com/proxy/wechat!getQrCode.action}")
	private String WECHAT_QRCODE_URL;
	@NacosValue(value = "${enable.ecitic.xiaochengxupay:true}", autoRefreshed = true)
	private boolean enableEciticXiaochengPay;
	@Value("${baidu.appId:mXWxfymXexkD9BIlXbFQZscL2fvoRXhz}")
	private String baiduAppId;
	@Value("${kuaishou.appId:ks686517471740005771}")
	private String kaishouAppId;
	@Value("${spring.mq.topic.oms}")
	private String OMS_MQ_TOPIC;
	/**
	 * 支付宝小程序支付地址（付工程师收款）
	 */
	private String ALIPAY_XIAOCHENGXU_PAY_URL = "alipays://platformapi/startapp?appId=2019060465478316&page=/pages/payment/index?orderId=";

	/**
	 * 支付工程师收款
	 *
	 * @param orderPayDTO
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	public PayGatewayDRO payMasterAmount(ZsOrderPayDTO orderPayDTO) throws OmsBaseException {
		Long orderId = orderPayDTO.getOrderId();
		Long workId = orderPayDTO.getWorkId();
		log.info("{} payMasterAmount orderPayDTO :{}", orderId, JSON.toJSONString(orderPayDTO));
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
		if (orderWork == null) {
			throw new OmsBaseException("工单不存在");
		}
		if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
			throw new OmsBaseException("订单已取消或完结");
		}
		Integer masterPayStatus = orderWork.getMasterPayStatus();
		if (Objects.equals(PayConsts.PAY_STATUS_DONE, masterPayStatus)) {
			throw new OmsBaseException("工程师收款已经支付");
		}

		// 待支付金额校验
		if (NumberUtil.isNotNullOrZero(orderPayDTO.getToPayAmount())) {
			if (!Objects.equals(orderPayDTO.getToPayAmount(), orderWork.getMasterAmount())) {
				throw new OmsBaseException("检测到费用信息发生了变化，请联系工程师进行确认");
			}
		}

		if (orderWork.getMasterAmount() == null || orderWork.getMasterAmount() <= 0) {
			throw new OmsBaseException("工程师收款金额为空");
		}

		if (NumberUtil.isNotNullOrZero(orderWork.getDepositAmount()) && !Objects.equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_DONE)) {
			throw new OmsBaseException("有存在未支付的定金，请先支付定金");
		}
		// 获取微信临时二维码（通过模版消息支付）
		// if (this.needWechatQrCode(orderWork, orderWork.getPlatWork(), orderPayDTO.getPayChannelId(),
		// 		orderPayDTO.getPayType())) {
		// 	String qrCode = this.getWechatQrcode(orderId, WechatQrConststs.QR_TYPE_MASTER_AMOUNT_PAY);
		// 	if (StringUtils.isNotBlank(qrCode)) {
		// 		return PayGatewayDRO.builder().qrCode(qrCode).build();
		// 	}
		// }
		// 获取支付宝小程序支付二维码
		if (this.needAliXiaoChengXuQrCode(orderWork.getPlatWork(),orderPayDTO.getPayChannelId(),orderPayDTO.getPayType())) {
			String qrCode = ALIPAY_XIAOCHENGXU_PAY_URL + orderWork.getOrderId();
			PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
			payGatewayDRO.setQrCode(qrCode);
			return payGatewayDRO;
		}

		// 获取渠道支付二维码 lhl-2020.12.03
		PayGatewayDRO payUrlOfQrcode = this.getChannelPayQrCode(orderWork, orderPayDTO.getPayChannelId());
		if (payUrlOfQrcode != null) {
			return payUrlOfQrcode;
		}

		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

		PayOrderDRO consume = null;
		PayGatewayDIO payGatewayDIO = new PayGatewayDIO();
		payGatewayDIO.setPlat(this.getPayPlat(orderWork.getPlatWork(), orderPayDTO.getPayChannelId(), orderWork.getServProductGroupId()));
		payGatewayDIO.setPayPlat(this.getPayPlat(orderWork.getPlatWork(), orderPayDTO.getPayChannelId(), orderWork.getServProductGroupId()));
		payGatewayDIO.setPayChannelId(orderPayDTO.getPayChannelId());
		payGatewayDIO.setPayType(orderPayDTO.getPayType());
		payGatewayDIO.setPayTargetChannelId(orderPayDTO.getPayTargetChannelId());
		payGatewayDIO.setPayTargetWay(orderPayDTO.getPayTargetType());
		payGatewayDIO.setSummary(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setPayTitle(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setAmount(orderWork.getMasterAmount());
		payGatewayDIO.setPayWayDIO(this.getPayWayDIO(orderPayDTO));
		payGatewayDIO.setTradeCategOneId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getOneId());
		payGatewayDIO.setTradeCategTwoId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getTwoId());
		payGatewayDIO.setTradeCategThreeId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getThirdId());
		payGatewayDIO.setAppId(AppEnum.APP_OMS.getAppId());
		payGatewayDIO.setAppName(AppEnum.getAppNameByAppId(AppEnum.APP_OMS.getAppId()));
		payGatewayDIO.setAppBizNo(String.valueOf(orderPayDTO.getOrderId()));
		String subBizNo = String.format("%s%s%s%s-%s", PayAmountTypeConsts.ORDER_IN_MASTER, orderPayDTO.getPayChannelId(),
				orderPayDTO.getPayType(), Optional.ofNullable(orderPayDTO.getPayTargetChannelId()).orElse(0),
				StringUtils.defaultIfBlank(orderPayDTO.getOpenId(), "")
		);
		payGatewayDIO.setAppSubBizNo(subBizNo);
		payGatewayDIO.setNoticMqTopic(OMS_MQ_TOPIC);
		payGatewayDIO.setNoticeMqTag(MessageQueueTagConsts.OMS_ORDERPAY);
		payGatewayDIO.setSyncResponse((orderPayDTO.getSyncFlag() == null || GlobalConsts.NO == orderPayDTO.getSyncFlag()) ? GlobalConsts.NO : GlobalConsts.YES);
		OmsPayRequestDTO orderPayExtDTO = BeanMapper.map(orderPayDTO, OmsPayRequestDTO.class);
		orderPayExtDTO.setAmountType(PayAmountTypeConsts.ORDER_IN_MASTER);
		payGatewayDIO.setNoticeMqExtendData(JSON.toJSONString(orderPayExtDTO));
		payGatewayDIO.setOperator(Optional.ofNullable(orderPayDTO.getOperator()).orElse("系统"));
		payGatewayDIO.setOperatorId(orderPayDTO.getOperatorId());
		payGatewayDIO.setOperatorType(orderPayDTO.getOperatorType());
		payGatewayDIO.setOperatorRemark(orderPayDTO.getOperatorRemark());
		// 银行转账，设置帐号信息
		if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_BANKTRANSFER)) {
			BankTransferPayDIO payAccountDIO = new BankTransferPayDIO();
			payAccountDIO.setPayAccount(orderPayDTO.getToBank());
			payAccountDIO.setPayer(orderPayDTO.getTransferor());
			payAccountDIO.setTransferCode(orderPayDTO.getTransferCode());
			payAccountDIO.setTransferTime(orderPayDTO.getTransferTime());
			payGatewayDIO.setPayWayDIO(payAccountDIO);
		}
		// 余额支付
		else if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_BALANCEAMOUNT)
				|| Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_CREDIT)) {
			// 厂商账号
			if (Objects.equals(FicoConsts.ACC_FACTORY, orderPayDTO.getAccountType())) {
				// 资金账户解冻并扣减余额
				consume = factoryAccountModifyBService.consume(orderPayDTO);
			}
		}

		// 业务数据 工单id, 操作人, 金额类型 业务数据会通过支付队列通知相应业务
		OmsPayRequestDTO omsPayRequestDTO = new OmsPayRequestDTO();
		omsPayRequestDTO.setPlat(orderPayDTO.getPlat());
		omsPayRequestDTO.setAppPlat(orderPayDTO.getAppPlat());
		omsPayRequestDTO.setVersion(orderPayDTO.getVersion());
		omsPayRequestDTO.setDisplayVersion(orderPayDTO.getDisplayVersion());
		omsPayRequestDTO.setOrderId(orderId);
		omsPayRequestDTO.setWorkId(workId);
		omsPayRequestDTO.setAmountType(PayAmountTypeConsts.ORDER_IN_MASTER);
		omsPayRequestDTO.setAgentType(orderPayDTO.getAgentType());
		omsPayRequestDTO.setOperator(orderPayDTO.getOperator());
		omsPayRequestDTO.setOperatorId(orderPayDTO.getOperatorId());
		omsPayRequestDTO.setOperatorType(orderPayDTO.getOperatorType());
		omsPayRequestDTO.setLongitude(orderPayDTO.getLongitude());
		omsPayRequestDTO.setLatitude(orderPayDTO.getLatitude());
		omsPayRequestDTO.setImageUrls(orderPayDTO.getImageUrls());
		if (!Objects.isNull(payGatewayDIO.getPayWayDIO())) {
			omsPayRequestDTO.setPayeeThirdAccountName(orderPayDTO.getCompanyName());//到账银行（收款账号）
			omsPayRequestDTO.setPayerThirdAccount(orderPayDTO.getTransferor());
			omsPayRequestDTO.setPayerThirdAccountBank(orderPayDTO.getToBank());
			//omsPayRequestDTO.setPayerType(GlobalConsts.OPERATE_USER_TYPE_USER);
		}
		payGatewayDIO.setNoticeMqExtendData(JSON.toJSONString(omsPayRequestDTO));

		// 支付宝支付 传产品信息过去
		if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_ALIPAY)) {
			AlipayGoodsDetailDIO goodsDetailDIO = new AlipayGoodsDetailDIO();
			goodsDetailDIO.setGoodsId(String.valueOf(orderWork.getShowProductId()));
			goodsDetailDIO.setPrice(payGatewayDIO.getAmount());
			goodsDetailDIO.setGoodsName(orderDetail.getProductInfo());
			goodsDetailDIO.setQuantity(1);
			payGatewayDIO.setAlipayGoodsDetails(Lists.newArrayList(goodsDetailDIO));
		}

		log.info("{} payMasterAmount支付入参：{}", orderId, JSON.toJSONString(payGatewayDIO));
		ResponseDTO<PayGatewayDRO> responseDTO = payGatewayRemoteService.pay(payGatewayDIO);
		log.info("{} payMasterAmount支付出参：{}", orderId, JSON.toJSONString(responseDTO));
		if (!responseDTO.isSuccess()) {
			throw new OmsBaseException(responseDTO.getMessage());
		}
		PayGatewayDRO payGatewayDRO = responseDTO.getData();
		// 资金帐号支付，流水号取消费返回的orderId
		if (consume != null && payGatewayDRO.getStatus() != null) {
			payGatewayDRO.getStatus().setInnerTradeNo(String.valueOf(consume.getOrderId()));
		}
		return payGatewayDRO;
	}

	/**
	 * 获取第三方渠道的支付二维码链接，如果订单不支持第三方二维码支付，返回null。
	 * @param orderWork
	 * @param payChannelId
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	public PayGatewayDRO getChannelPayQrCode(OrderWork orderWork, Integer payChannelId) throws OmsBaseException {

		boolean isPayPlatformChannel = Objects.equals(PayConsts.PAY_CHANNEL_PLATFORM_CHANNEL, payChannelId);
		Integer channelId = orderWork.getChannelId();
		Long orderId = orderWork.getOrderId();

		if (Objects.equals(channelId, DaoJia58Consts.CHANNEL_ID_API)) {
			log.info("渠道为：58到家直约API，支付为：58二维码支付");
			if (isPayPlatformChannel) {
				String payUrl = this.getCachedPayUrl(orderId);
				if (StringUtils.isBlank(payUrl)) {
					payUrl = daoJia58Service.getSupplyPayUrl(orderId);
					this.cachePayUrl(orderId, payUrl);
				}
				if (StringUtils.isNotBlank(payUrl)) {
					PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
					payGatewayDRO.setQrCode(payUrl);
					return payGatewayDRO;
				}
			}

			throw new OmsBaseException("获取渠道支付二维码失败");
		}

		// XieWenBing 雅管家渠道支付......
		// remove at 2021-01-12
		/**
		 if (yajuleService.determinYajuleChannel(channelId)) {
		 log.info("渠道为：雅管家平台渠道，支付为：雅管家二维码支付");
		 if (isPayPlatformChannel) {
		 String payUrl = this.getCachedPayUrl(orderId);
		 if (StringUtils.isBlank(payUrl)) {
		 payUrl = yajuleService.getPayUrl(orderId);
		 this.cachePayUrl(orderId, payUrl);
		 }
		 if (StringUtils.isNotBlank(payUrl)) {
		 return PayGatewayDRO.builder().qrCode(payUrl).build();
		 }
		 }

		 throw new OmsBaseException("获取渠道支付二维码失败");
		 }
		 **/

		// XieWenBing 国美管家渠道支付...... 2020-11-09
		if (Objects.equals(orderWork.getChannelId(), OrderConsts.CHANNEL_ID_GOME_GJ_JDWX) ||
				Objects.equals(orderWork.getChannelId(), OrderConsts.CHANNEL_ID_GOME_GJ_ZX)) {
			log.info("渠道为：国美管家，支付为：国美管家二维码支付，【{}】【{}】", orderWork.getOrderId(), payChannelId);
			if (isPayPlatformChannel) {
				String payUrl = gmgjService.getPayUrl(orderWork.getOrderId(),orderWork.getWorkId());
				if (StringUtils.isNotBlank(payUrl)) {
					PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
					payGatewayDRO.setQrCode(payUrl);
					return payGatewayDRO;
				}
			}

			throw new OmsBaseException("获取渠道支付二维码失败");
		}

		// huangyifeng 58精选支付
		if (Objects.equals(channelId, Tc58Consts.CHANNEL_ID_JX) ||
				Objects.equals(channelId, Tc58Consts.CHANNEL_ID_JX_PIPE) ||
				Objects.equals(channelId, Tc58Consts.CHANNEL_ID_JX_CLOCK) ||
				Objects.equals(channelId, Tc58Consts.CHANNEL_ID_JX_APARTMENT)) {

			Tc58Consts.ChannelInfo channelInfo = Tc58Consts.getChannelInfo(channelId);
			log.info("渠道为："+ channelInfo.getName() +"，支付为：58二维码支付");

			if (isPayPlatformChannel) {
				PayLinkInfo payLinkInfo = this.getCachedPayLinkInfo(orderId);
				if (payLinkInfo != null) {
					PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
					payGatewayDRO.setQrCode(payLinkInfo.getPayLink());
					payGatewayDRO.setChannelPayTypeMsg(payLinkInfo.getChannelPayTypeMsg());
					return payGatewayDRO;
				}

				// 创建 CdsHttpCallClient 对象
				CdsHttpCallClient client = CdsHttpCallClient.newInstance(
						CdsConsts.HttpCall.BASE_URL,
						CdsConsts.HttpCall.MODEL_NAME,
						CdsConsts.HttpCall.SECRET_KEY
				);
				// 封装请求参数
				ApplyPayLinkDIO dio = new ApplyPayLinkDIO();
				dio.setZmnOrderId(orderWork.getWorkId());
				dio.setAmount(orderWork.getMasterAmount());
				dio.setAmountType(ApplyPayLinkDIO.AmountType.REST);
				// 获取渠道支付链接
				CdsHttpCallResult<ApplyPayLinkDRO> result = client.applyPayLink(dio);

				if (result.isStatusBool()) {
					ApplyPayLinkDRO payLinkDRO = result.getData();
					if (Objects.nonNull(payLinkDRO) && StringUtils.isNotBlank(payLinkDRO.getPayLink())) {
						String payLinkUrl = payLinkDRO.getPayLink();
						if (ApplyPayLinkDRO.PayLinkType.IMG == payLinkDRO.getPayLinkType()) {
							payLinkUrl = String.format("%s?isQrCodeImg=true", payLinkUrl);
						}

						String channelPayTypeMsg = null;
						List<ApplyPayLinkDRO.PayAppType> payAppTypes = payLinkDRO.getPayAppTypes();
						if (payAppTypes != null && !payAppTypes.isEmpty()) {
							StringJoiner stringJoiner = new StringJoiner("/");
							for (ApplyPayLinkDRO.PayAppType item : payAppTypes) {
								stringJoiner.add(item.getName());
							}

							channelPayTypeMsg = String.format("请使用%s扫码支付", stringJoiner.toString());
						}

						payLinkInfo = new PayLinkInfo();
						payLinkInfo.setPayLink(payLinkUrl);
						payLinkInfo.setChannelPayTypeMsg(channelPayTypeMsg);
						this.cachePayLinkInfo(orderId, payLinkInfo);

						PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
						payGatewayDRO.setQrCode(payLinkUrl);
						payGatewayDRO.setChannelPayTypeMsg(channelPayTypeMsg);
						return payGatewayDRO;
					}
				} else if (!result.isStatusBool() && result.getMessage().indexOf(Tc58Consts.LAST_PAY_MONEY) > 0) {
					throw new OmsBaseException(
							AppConsts.APP_PAY_FLAG_CHANNEL_PRICE,
							String.format(
									"该订单剩余应收不能低于：%s元，请重新选择",
									result.getMessage().split("lastPayMoney =")[1]
							)
					);
				}
			}

			throw new OmsBaseException("请引导用户在58同城平台支付");
		}

		// 到位接口系列渠道 2020.12.22 by lhl
		if (Objects.equals(orderWork.getChannelId(), DaoweiConsts.CHANNEL_ID_DTW) ||
				Objects.equals(orderWork.getChannelId(), DaoweiConsts.CHANNEL_ID_APP) ||
				Objects.equals(orderWork.getChannelId(), DaoweiConsts.CHANNEL_ID_KYX) ||
				Objects.equals(orderWork.getChannelId(), DaoweiConsts.CHANNEL_ID_ZX)) {
			log.info("channelId:{},渠道为：{}，支付为：渠道二维码支付",orderWork.getChannelId(),
					DaoweiConsts.getChannelName(orderWork.getChannelId()));

			if (isPayPlatformChannel) {
				String qrCodeImgUrl = this.getCachedPayUrl(orderId);
				String channelPayTypeMsg = null;
				if (StringUtils.isBlank(qrCodeImgUrl)) {
//					qrCodeImgUrl = daoweiService.requestPayQrCodeImgUrl(orderId);
					// 到位返回的是支付二维码图片的地址，需要标明该地址是图片，但从2021-02-23开始，到位修改了线上的接口，
					// 不再返回二维码图片地址，改用支付链接地址，同时支持微信和支付宝支付了，所以不再标识该地址为图片地址 lhl-2021.02.24
					//qrCodeImgUrl = String.format("%s?isQrCodeImg=true", qrCodeImgUrl);
					// 调用CDS获取支付链接
					// 创建 CdsHttpCallClient 对象
					CdsHttpCallClient client = CdsHttpCallClient.newInstance(
							CdsConsts.HttpCall.BASE_URL,
							CdsConsts.HttpCall.MODEL_NAME,
							CdsConsts.HttpCall.SECRET_KEY
					);
					// 封装请求参数
					ApplyPayLinkDIO dio = new ApplyPayLinkDIO();
					dio.setZmnOrderId(orderWork.getWorkId());
					dio.setAmount(orderWork.getMasterAmount());
					dio.setAmountType(ApplyPayLinkDIO.AmountType.REST);
					// 获取渠道支付链接
					log.info("【到位】获取支付链接的入参:{}",dio);
					CdsHttpCallResult<ApplyPayLinkDRO> result = client.applyPayLink(dio);
					log.info("【到位】获取支付链接的响应:{}",result);

					if (result.isStatusBool()) {
						ApplyPayLinkDRO payLinkDRO = result.getData();
						if (Objects.nonNull(payLinkDRO) && StringUtils.isNotBlank(payLinkDRO.getPayLink())) {
							String payLinkUrl = payLinkDRO.getPayLink();
							List<ApplyPayLinkDRO.PayAppType> payAppTypes = payLinkDRO.getPayAppTypes();
							if (payAppTypes != null && !payAppTypes.isEmpty()) {
								StringJoiner stringJoiner = new StringJoiner("/");
								for (ApplyPayLinkDRO.PayAppType item : payAppTypes) {
									stringJoiner.add(item.getName());
								}
								channelPayTypeMsg = String.format("请使用%s扫码支付", stringJoiner.toString());
							}
							qrCodeImgUrl = payLinkUrl;

						}
					} else {
						throw new OmsBaseException(String.format(
								"获取渠道收款码失败：%s",
								result.getMessage()
						));
					}
					this.cachePayUrl(orderId, qrCodeImgUrl);
				}
				if (StringUtils.isNotBlank(qrCodeImgUrl)) {
					PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
					payGatewayDRO.setQrCode(qrCodeImgUrl);
					payGatewayDRO.setChannelPayTypeMsg(channelPayTypeMsg);
					return payGatewayDRO;
				}
				throw new OmsBaseException("请引导用户在到位平台支付");
			}
		}

		// 支持渠道收款的标准API对接渠道
		if (ChannelConsts.CHANNEL_OPENAPI_SUPPORT_PAYLINK.get(orderWork.getChannelId()) != null) {
			if (isPayPlatformChannel) {
				PayLinkInfo payLinkInfo = this.getCachedPayLinkInfo(orderId, orderWork.getMasterAmount());
				if (payLinkInfo != null) {
					PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
					payGatewayDRO.setQrCode(payLinkInfo.getPayLink());
					payGatewayDRO.setChannelPayTypeMsg(payLinkInfo.getChannelPayTypeMsg());
					return payGatewayDRO;
				}

				// 创建 CdsHttpCallClient 对象
				CdsHttpCallClient client = CdsHttpCallClient.newInstance(
						CdsConsts.HttpCall.BASE_URL,
						CdsConsts.HttpCall.MODEL_NAME,
						CdsConsts.HttpCall.SECRET_KEY
				);
				// 封装请求参数
				ApplyPayLinkDIO dio = new ApplyPayLinkDIO();
				dio.setZmnOrderId(orderWork.getWorkId());
				dio.setAmount(orderWork.getMasterAmount());
				dio.setAmountType(ApplyPayLinkDIO.AmountType.REST);
				// 获取渠道支付链接
				CdsHttpCallResult<ApplyPayLinkDRO> result = client.applyPayLink(dio);

				if (result.isStatusBool()) {
					ApplyPayLinkDRO payLinkDRO = result.getData();
					if (Objects.nonNull(payLinkDRO) && StringUtils.isNotBlank(payLinkDRO.getPayLink())) {
						String payLinkUrl = payLinkDRO.getPayLink();
						if (ApplyPayLinkDRO.PayLinkType.IMG == payLinkDRO.getPayLinkType()) {
							payLinkUrl = String.format("%s?isQrCodeImg=true", payLinkUrl);
						}

						String channelPayTypeMsg = null;
						List<ApplyPayLinkDRO.PayAppType> payAppTypes = payLinkDRO.getPayAppTypes();
						if (payAppTypes != null && !payAppTypes.isEmpty()) {
							StringJoiner stringJoiner = new StringJoiner("/");
							for (ApplyPayLinkDRO.PayAppType item : payAppTypes) {
								stringJoiner.add(item.getName());
							}

							channelPayTypeMsg = String.format("请使用%s扫码支付", stringJoiner.toString());
						}

						payLinkInfo = new PayLinkInfo();
						payLinkInfo.setPayLink(payLinkUrl);
						payLinkInfo.setChannelPayTypeMsg(channelPayTypeMsg);
						this.cachePayLinkInfo(orderId, payLinkInfo, orderWork.getMasterAmount());

						PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
						payGatewayDRO.setQrCode(payLinkUrl);
						payGatewayDRO.setChannelPayTypeMsg(channelPayTypeMsg);
						return payGatewayDRO;
					}
				} else {
					throw new OmsBaseException(String.format(
							"获取渠道收款码失败：%s",
							result.getMessage()
					));
				}
			}
		}

		// 百度 二级渠道ID：41325、41326、41359、41360、41361、41362、41363
		// 41491、41492、41494、41495、41496、41497、41498
//		if (ChannelConsts.CHANNEL_ID_BAIDU_PAY_ALERT.contains(channelId)) {
//			log.info("渠道为：百度APP，支付为：引导用户在百度APP上完成订单支付");
//			if (isPayPlatformChannel) {
//				String payUrl = this.getCachedPayUrl(orderId);
//				if (StringUtils.isNotBlank(payUrl)) {
//					PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
//					payGatewayDRO.setQrCode(payUrl);
//					return payGatewayDRO;
//				}
//			}
//
//			throw new OmsBaseException("此订单需在百度APP上支付，请引导用户打开百度APP，完成订单支付。");
//		}

		// E34渠道
//		if (ChannelConsts.CHANNEL_ID_GZDCB_PAY_ALERT.contains(channelId)) {
//			if (isPayPlatformChannel) {
//				String payUrl = this.getCachedPayUrl(orderId);
//				if (StringUtils.isNotBlank(payUrl)) {
//					PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
//					payGatewayDRO.setQrCode(payUrl);
//					return payGatewayDRO;
//				}
//			}
//			throw new OmsBaseException("请引导用户在贵州多彩宝支付服务费，联系贵阳办公室确认收款后，修改预付款。");
//		}

		// 58同城 二级渠道ID：34781, 34783
//		if (ChannelConsts.CHANNEL_ID_58TONGCHENG_PAY_ALERT.contains(channelId)) {
//			log.info("渠道为：58同城APP，支付为：引导用户在58同城APP上完成订单支付");
//			if (isPayPlatformChannel) {
//				String payUrl = this.getCachedPayUrl(orderId);
//				if (StringUtils.isNotBlank(payUrl)) {
//					PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
//					payGatewayDRO.setQrCode(payUrl);
//					return payGatewayDRO;
//				}
//			}
//
//			throw new OmsBaseException("此订单需在58同城APP上支付，请引导用户打开58同城APP，完成订单支付。");
//		}


		return null;
	}

	/**
	 * 校验渠道订单配置
	 *
	 * @param version
	 * @param orderWork
	 * @return
	 * @throws OmsBaseException
	 */
	public void checkChannelOrderConfig(Integer version, OrderWork orderWork) throws OmsBaseException {
		ConfOrderChannelDRO confOrderChannelDRO = confOrderChannelBService.getByChannelId(orderWork.getChannelId());
		if (Objects.isNull(confOrderChannelDRO)) {
			return;
		}

		// 是否第三方支付
		boolean needGuideThirdPartPay = Objects.equals(confOrderChannelDRO.getGuideThirdPartPay(), GlobalConsts.YES);
		if (!needGuideThirdPartPay) {
			return;
		}

		boolean needShowPayQr = Objects.equals(confOrderChannelDRO.getShowPayQr(), GlobalConsts.YES);
		String payPlat = StringUtils.isNotBlank(confOrderChannelDRO.getPayPlat()) ? confOrderChannelDRO.getPayPlat() : "";
		boolean hasPayExplain = StringUtil.isNotBlank(confOrderChannelDRO.getPayExplain());
		log.info("workId={} APP版本号：{} 渠道ID：{}，支付为：引导用户在{}上完成订单支付", orderWork.getWorkId(), version, confOrderChannelDRO.getChannelId(), payPlat);

		// 兼容旧版本
		if (Objects.nonNull(version) && version < 103) {
			needShowPayQr = false;
		}

		String msg;
		if (needShowPayQr) {
			msg = String.format("此订单可在%s上支付尾款，你可以查看支付指引，引导用户完成支付，也可以在本APP上立即支付。", payPlat);
		} else {
			msg = String.format("此订单需在%s上支付，请引导用户打开%s，完成订单支付。", payPlat, payPlat);
		}
		if (hasPayExplain) {
			throw new OmsBaseException(AppConsts.APP_PAY_FLAG_CHANNEL_GUIDE, msg);
		} else if (needShowPayQr) {
			msg = String.format("此订单可在%s上支付尾款，请引导用户完成支付，也可以在本APP上立即支付。", payPlat);
			throw new OmsBaseException(AppConsts.APP_PAY_FLAG_CHANNEL_GUIDE_NO_EXPLAIN, msg);
		}
		throw new OmsBaseException(msg);
	}

	/**
	 * 渠道二次支付
	 *
	 * @param orderPayDTO
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void paySecondChannelPay(ZsOrderPayDTO orderPayDTO) throws OmsBaseException {
		Long orderId = orderPayDTO.getOrderId();
		Long workId = orderPayDTO.getWorkId();
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);

		if (orderWork == null) {
			throw new OmsBaseException("工单不存在.");
		}

		// 状态是已完成的订单，不在修改渠道预付款，改为单独记录为渠道非正常支付金额  lhl-2021.01.25
		if (orderWork.getStatus() >= OrderStatusConsts.ORDER_STATUS_COMPLETE) {
			AbnormalPayment abnormalPayment = new AbnormalPayment();
			abnormalPayment.setOrderId(orderWork.getOrderId());
			abnormalPayment.setChannelId(orderWork.getChannelId());
			abnormalPayment.setOrderStatus(orderWork.getStatus());
			abnormalPayment.setOrderResult(orderWork.getResultStatus());
			abnormalPayment.setPayAmount(orderPayDTO.getPayAmount());
			abnormalPayment.setFacadeId(orderPayDTO.getFacadeId());
			abnormalPayment.setCreater(orderPayDTO.getOperator());

			abnormalPaymentService.save(abnormalPayment);

			String addRemark = "工单完成后同步补尾款金额，该金额不记录进工单，但会记录进ERP渠道结算";
			String oldRemark = orderPayDTO.getOperatorRemark();
			if (StringUtils.isBlank(oldRemark)) {
				orderPayDTO.setOperatorRemark(addRemark);
			}
			else {
				orderPayDTO.setOperatorRemark(String.format("%s，%s", oldRemark, addRemark));
			}
			return;
		}

		// 是否抵扣师傅收款额
		boolean subMasterAmount = Optional.ofNullable(orderPayDTO.getSubMasterAmount()).orElse(true);

		if (subMasterAmount) {
			Integer masterPayStatus = orderWork.getMasterPayStatus();
			if (Objects.equals(PayConsts.PAY_STATUS_DONE, masterPayStatus)) {
				throw new OmsBaseException("工程师收款已经支付");
			}

			if (orderWork.getMasterAmount() == null || orderWork.getMasterAmount() <= 0) {
				throw new OmsBaseException("工程师收款金额为空");
			}
		}

		// 更新预付金额， 预付金额 = 工程师收款金额 + 预付
		// 2. 改支付状态
		OrderWork updateAmount = new OrderWork();
		updateAmount.setOrderId(orderId);
		updateAmount.setWorkId(workId);
		updateAmount.setPayStatus(PayConsts.PAY_STATUS_DONE);
		updateAmount.setChannelPrepayStatus(PayConsts.PAY_STATUS_DONE);
		updateAmount.setChannelPrepayAmount(Optional.ofNullable(orderPayDTO.getPayAmount()).orElse(0) + Optional.ofNullable(orderWork.getChannelPrepayAmount()).orElse(0));

		if (subMasterAmount) {
			updateAmount.setMasterAmount(0);
		}
		orderWorkAmountService.updateSecondChannelPay(updateAmount);
	}

	/**
	 * 渠道二次支付，并将工单状态置为成功
	 *
	 * @param orderPayDTO
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	public void paySecondChannelPayAndOrderComplete(ZsOrderPayDTO orderPayDTO) throws OmsBaseException {
		paySecondChannelPay(orderPayDTO);

		// 渠道支付通知push推送
		try {
			OrderWork dbOrderWork = orderWorkService.findOrderWorkByKey(orderPayDTO.getOrderId(), orderPayDTO.getWorkId());
			Map<String, Object> params = Maps.newHashMap();
			params.put("order_id", String.valueOf(orderPayDTO.getOrderId()));
			params.put("work_id", String.valueOf(orderPayDTO.getWorkId()));
			params.put("amount", String.valueOf(AmountUtil.fen2Yuan(orderPayDTO.getPayAmount()).doubleValue()));
			messageSendAppService.pushAppMessageInfo(MessageRuleIdConsts.PUSH_MSG_RULEID_ORDER_PAY, JSON.toJSONString(params), dbOrderWork);
		} catch (Exception e) {
			log.info(e.getMessage(), e);
		}

		// 将工单状态置为成功
		CompleteDTO completeDTO = new CompleteDTO();
		completeDTO.setOrderId(orderPayDTO.getOrderId());
		completeDTO.setWorkId(orderPayDTO.getWorkId());
		completeDTO.setOperatorLogRemark(orderPayDTO.getOperatorRemark());
		zsMasterWorkBService.completeOrder(completeDTO);
	}

	/**
	 * 啄木鸟预付款支付
	 * @param orderPayDTO
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	public PayGatewayDRO payPrepaidAmount(ZsOrderPayDTO orderPayDTO) throws OmsBaseException {
		Long orderId = orderPayDTO.getOrderId();
		Long workId = orderPayDTO.getWorkId();
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
		if (orderWork == null) {
			throw new OmsBaseException("工单不存在");
		}
		if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
			throw new OmsBaseException("订单已取消或完结");
		}
		Integer prepayStatus = orderWork.getPrepayStatus();
		if (Objects.equals(PayConsts.PAY_STATUS_DONE, prepayStatus)) {
			throw new OmsBaseException("预付款已经支付");
		}
		if (orderWork.getPrepayAmount() == null || orderWork.getPrepayAmount() <= 0) {
			throw new OmsBaseException("预付款为空");
		}

		// 附加请求数据，供支付后续业务处理
		OmsPayRequestDTO omsPayRequestDTO = new OmsPayRequestDTO();
		omsPayRequestDTO.setOrderId(orderId);
		omsPayRequestDTO.setWorkId(workId);
		omsPayRequestDTO.setAmountType(PayAmountTypeConsts.ORDER_IN_PREPAY);
		omsPayRequestDTO.setAgentType(orderPayDTO.getAgentType());
		omsPayRequestDTO.setOperator(orderPayDTO.getOperator());
		omsPayRequestDTO.setOperatorId(orderPayDTO.getOperatorId());
		omsPayRequestDTO.setOperatorType(orderPayDTO.getOperatorType());
		omsPayRequestDTO.setLongitude(orderPayDTO.getLongitude());
		omsPayRequestDTO.setLatitude(orderPayDTO.getLatitude());
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);
		PayGatewayDIO payGatewayDIO = new PayGatewayDIO();
		payGatewayDIO.setPlat(orderPayDTO.getPlat());
		payGatewayDIO.setPayPlat(orderPayDTO.getPlat());
		payGatewayDIO.setPayChannelId(orderPayDTO.getPayChannelId());
		payGatewayDIO.setPayType(orderPayDTO.getPayType());
		payGatewayDIO.setPayTargetChannelId(orderPayDTO.getPayTargetChannelId());
		payGatewayDIO.setPayTargetWay(orderPayDTO.getPayTargetType());
		payGatewayDIO.setSummary(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setPayTitle(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setAmount(orderWork.getPrepayAmount());
		payGatewayDIO.setSyncResponse((orderPayDTO.getSyncFlag() == null || GlobalConsts.NO == orderPayDTO.getSyncFlag()) ? GlobalConsts.NO : GlobalConsts.YES);
		payGatewayDIO.setPayWayDIO(this.getPayWayDIO(orderPayDTO));
		payGatewayDIO.setTradeCategOneId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_O2O_PAY.getOneId());
		payGatewayDIO.setTradeCategTwoId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_O2O_PAY.getTwoId());
		payGatewayDIO.setTradeCategThreeId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_O2O_PAY.getThirdId());
		payGatewayDIO.setAppId(AppEnum.APP_OMS.getAppId());
		payGatewayDIO.setAppName(AppEnum.getAppNameByAppId(AppEnum.APP_OMS.getAppId()));
		payGatewayDIO.setAppBizNo(String.valueOf(orderPayDTO.getOrderId()));
		String subBizNo = String.format("%s%s%s%s-%s", PayAmountTypeConsts.ORDER_IN_PREPAY, orderPayDTO.getPayChannelId(),
				orderPayDTO.getPayType(), Optional.ofNullable(orderPayDTO.getPayTargetChannelId()).orElse(0),
				StringUtils.defaultIfBlank(orderPayDTO.getOpenId(), "")
		);
		payGatewayDIO.setAppSubBizNo(subBizNo);
		payGatewayDIO.setNoticMqTopic(OMS_MQ_TOPIC);
		payGatewayDIO.setNoticeMqTag(MessageQueueTagConsts.OMS_ORDERPAY);
		payGatewayDIO.setNoticeMqExtendData(JSON.toJSONString(omsPayRequestDTO));
		payGatewayDIO.setOperator(orderPayDTO.getOperator());
		payGatewayDIO.setOperatorId(orderPayDTO.getOperatorId());
		payGatewayDIO.setOperatorType(orderPayDTO.getOperatorType());
		payGatewayDIO.setOperatorRemark(orderPayDTO.getOperatorRemark());
		log.info("{} payPrepaidAmount 支付入参：{}", orderId, JSON.toJSONString(payGatewayDIO));
		ResponseDTO<PayGatewayDRO> responseDTO = payGatewayRemoteService.pay(payGatewayDIO);
		log.info("{} payPrepaidAmount 支付出参：{}", orderId, JSON.toJSONString(responseDTO));
		if (!responseDTO.isSuccess()) {
			throw new OmsBaseException(responseDTO.getMessage());
		}

		return responseDTO.getData();
	}

	/**
	 * 支付定金
	 *
	 * @param orderPayDTO
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	public PayGatewayDRO payDepositAmount(ZsOrderPayDTO orderPayDTO) throws OmsBaseException {
		Long orderId = orderPayDTO.getOrderId();
		Long workId = orderPayDTO.getWorkId();
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);

		if (orderWork == null) {
			throw new OmsBaseException("工单不存在");
		}
		if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
			throw new OmsBaseException("订单已取消");
		}
		if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_COMPLETE) {
			throw new OmsBaseException("订单已完结");
		}
		Integer masterPayStatus = orderWork.getDepositStatus();
		if (Objects.equals(PayConsts.PAY_STATUS_DONE, masterPayStatus)) {
			throw new OmsBaseException("定金已经支付");
		}

		if (orderWork.getDepositAmount() == null || orderWork.getDepositAmount() <= 0) {
			throw new OmsBaseException("定金为空");
		}

		// XieWenBing 58到家直约的订单不提供定金支付
		if (orderWork.getChannelId() == OrderConsts.CHANNEL_ID_DJ58_DAG) {
			throw new OmsBaseException("58到家直约平台的订单不支持支付定金");
		}

		// 获取微信临时二维码（通过模版消息支付）
		if (this.needWechatQrCode(orderWork, orderWork.getPlatWork(), orderPayDTO.getPayChannelId(), orderPayDTO.getPayType())) {
			String qrCode = this.getWechatQrcode(orderId, WechatQrConststs.QR_TYPE_MASTER_DEPOSIT_AMOUNT_PAY);
			log.info("定金模版消息支付==>platWork:{},payChannelId:{},payType:{},qrCode:{}",
					orderWork.getPlatWork(), orderPayDTO.getPayChannelId(), orderPayDTO.getPayType(), qrCode);
//			String qrCode = this.getWechatQrcode(orderPayDTO.getOrderId(), "TempDepositPay", orderPayDTO.getOperator());
			if (StringUtils.isNotBlank(qrCode)) {
				PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
				payGatewayDRO.setQrCode(qrCode);
				return payGatewayDRO;
			}
		}

		// 附加请求数据，供支付后续业务处理
		OmsPayRequestDTO omsPayRequestDTO = new OmsPayRequestDTO();
		omsPayRequestDTO.setPlat(orderPayDTO.getPlat());
		omsPayRequestDTO.setAppPlat(orderPayDTO.getAppPlat());
		omsPayRequestDTO.setVersion(orderPayDTO.getVersion());
		omsPayRequestDTO.setDisplayVersion(orderPayDTO.getDisplayVersion());
		omsPayRequestDTO.setOrderId(orderId);
		omsPayRequestDTO.setWorkId(workId);
		omsPayRequestDTO.setAmountType(PayAmountTypeConsts.ORDER_IN_DEPOSIT);
		omsPayRequestDTO.setAgentType(orderPayDTO.getAgentType());
		omsPayRequestDTO.setOperator(orderPayDTO.getOperator());
		omsPayRequestDTO.setOperatorId(orderPayDTO.getOperatorId());
		omsPayRequestDTO.setOperatorType(orderPayDTO.getOperatorType());
		omsPayRequestDTO.setLongitude(orderPayDTO.getLongitude());
		omsPayRequestDTO.setLatitude(orderPayDTO.getLatitude());
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

		PayGatewayDIO payGatewayDIO = new PayGatewayDIO();
		payGatewayDIO.setPlat(orderPayDTO.getPlat());
		payGatewayDIO.setPayPlat(orderPayDTO.getPlat());
		payGatewayDIO.setPayChannelId(orderPayDTO.getPayChannelId());
		payGatewayDIO.setPayType(orderPayDTO.getPayType());
		payGatewayDIO.setPayTargetChannelId(orderPayDTO.getPayTargetChannelId());
		payGatewayDIO.setPayTargetWay(orderPayDTO.getPayTargetType());
		payGatewayDIO.setSummary(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setPayTitle(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setAmount(orderWork.getDepositAmount());
		payGatewayDIO.setSyncResponse((orderPayDTO.getSyncFlag() == null || GlobalConsts.NO == orderPayDTO.getSyncFlag()) ? GlobalConsts.NO : GlobalConsts.YES);
		payGatewayDIO.setPayWayDIO(this.getPayWayDIO(orderPayDTO));
		payGatewayDIO.setTradeCategOneId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getOneId());
		payGatewayDIO.setTradeCategTwoId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getTwoId());
		payGatewayDIO.setTradeCategThreeId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getThirdId());
		payGatewayDIO.setAppId(AppEnum.APP_OMS.getAppId());
		payGatewayDIO.setAppName(AppEnum.getAppNameByAppId(AppEnum.APP_OMS.getAppId()));
		payGatewayDIO.setAppBizNo(String.valueOf(orderPayDTO.getOrderId()));
		String subBizNo = String.format("%s%s%s%s-%s", PayAmountTypeConsts.ORDER_IN_DEPOSIT, orderPayDTO.getPayChannelId(),
				orderPayDTO.getPayType(), Optional.ofNullable(orderPayDTO.getPayTargetChannelId()).orElse(0),
				StringUtils.defaultIfBlank(orderPayDTO.getOpenId(), "")
		);
		payGatewayDIO.setAppSubBizNo(subBizNo);
		payGatewayDIO.setNoticMqTopic(OMS_MQ_TOPIC);
		payGatewayDIO.setNoticeMqTag(MessageQueueTagConsts.OMS_ORDERPAY);
		payGatewayDIO.setNoticeMqExtendData(JSON.toJSONString(omsPayRequestDTO));
		payGatewayDIO.setOperator(orderPayDTO.getOperator());
		payGatewayDIO.setOperatorId(orderPayDTO.getOperatorId());
		payGatewayDIO.setOperatorType(orderPayDTO.getOperatorType());
		payGatewayDIO.setOperatorRemark(orderPayDTO.getOperatorRemark());
		log.info("{} payDepositAmount 支付入参：{}", orderId, JSON.toJSONString(payGatewayDIO));
		ResponseDTO<PayGatewayDRO> responseDTO = payGatewayRemoteService.pay(payGatewayDIO);
		log.info("{} payDepositAmount 支付出参：{}", orderId, JSON.toJSONString(responseDTO));
		if (!responseDTO.isSuccess()) {
			throw new OmsBaseException(responseDTO.getMessage());
		}

		return responseDTO.getData();
	}

	/**
	 * 支付定金
	 *
	 * @param orderPayDTO
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	public PayGatewayDRO multipleVisitPayDepositAmount(ZsOrderPayDTO orderPayDTO) throws OmsBaseException {
		Long orderId = orderPayDTO.getOrderId();
		Long workId = orderPayDTO.getWorkId();
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);

		if (orderWork == null) {
			throw new OmsBaseException("工单不存在");
		}
		if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
			throw new OmsBaseException("订单已取消");
		}
		if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_COMPLETE) {
			throw new OmsBaseException("订单已完结");
		}
		/*Integer masterPayStatus = orderWork.getDepositStatus();
		if (Objects.equals(PayConsts.PAY_STATUS_DONE, masterPayStatus)) {
			throw new OmsBaseException("定金已经支付");
		}

		if (orderWork.getDepositAmount() == null || orderWork.getDepositAmount() <= 0) {
			throw new OmsBaseException("定金为空");
		}*/

		// XieWenBing 58到家直约的订单不提供定金支付
		if (orderWork.getChannelId() == OrderConsts.CHANNEL_ID_DJ58_DAG) {
			throw new OmsBaseException("58到家直约平台的订单不支持支付定金");
		}

		// 获取微信临时二维码（通过模版消息支付）
		if (this.needWechatQrCode(orderWork, orderWork.getPlatWork(), orderPayDTO.getPayChannelId(), orderPayDTO.getPayType())) {
			String qrCode = this.getWechatQrcode(orderId, WechatQrConststs.QR_TYPE_MASTER_DEPOSIT_AMOUNT_PAY);
			log.info("定金模版消息支付==>platWork:{},payChannelId:{},payType:{},qrCode:{}",
					orderWork.getPlatWork(), orderPayDTO.getPayChannelId(), orderPayDTO.getPayType(), qrCode);
//			String qrCode = this.getWechatQrcode(orderPayDTO.getOrderId(), "TempDepositPay", orderPayDTO.getOperator());
			if (StringUtils.isNotBlank(qrCode)) {
				PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
				payGatewayDRO.setQrCode(qrCode);
				return payGatewayDRO;
			}
		}

		// 待支付不存在
		OrderPay orderPay = null;
		if (NumberUtil.isNotNullOrZero(orderPayDTO.getOrderPayId())) {
			orderPay = orderPayService.findOrderPayByKeySrcMaster(orderWork.getOrderId(), orderPayDTO.getOrderPayId());
		}

		/*if (Objects.isNull(orderPay)) {
			throw new OmsBaseException("当前支付已取消");
		}*/
		Integer count = orderPayService.countByOrderIdAndWorkIdSrcMaster(orderWork.getOrderId(), orderWork.getWorkId());

		// 附加请求数据，供支付后续业务处理
		OmsPayRequestDTO omsPayRequestDTO = new OmsPayRequestDTO();
		omsPayRequestDTO.setPlat(orderPayDTO.getPlat());
		omsPayRequestDTO.setAppPlat(orderPayDTO.getAppPlat());
		omsPayRequestDTO.setVersion(orderPayDTO.getVersion());
		omsPayRequestDTO.setDisplayVersion(orderPayDTO.getDisplayVersion());
		omsPayRequestDTO.setOrderId(orderId);
		omsPayRequestDTO.setWorkId(workId);
		omsPayRequestDTO.setAmountType(PayAmountTypeConsts.ORDER_IN_DEPOSIT);
		omsPayRequestDTO.setAgentType(orderPayDTO.getAgentType());
		omsPayRequestDTO.setOperator(orderPayDTO.getOperator());
		omsPayRequestDTO.setOperatorId(orderPayDTO.getOperatorId());
		omsPayRequestDTO.setOperatorType(orderPayDTO.getOperatorType());
		omsPayRequestDTO.setLongitude(orderPayDTO.getLongitude());
		omsPayRequestDTO.setLatitude(orderPayDTO.getLatitude());
		omsPayRequestDTO.setAcceptanceId(orderPayDTO.getAcceptanceId());
		omsPayRequestDTO.setOrderPayId(orderPayDTO.getOrderPayId());
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

		PayGatewayDIO payGatewayDIO = new PayGatewayDIO();
		payGatewayDIO.setPlat(orderPayDTO.getPlat());
		payGatewayDIO.setPayPlat(orderPayDTO.getPlat());
		payGatewayDIO.setPayChannelId(orderPayDTO.getPayChannelId());
		payGatewayDIO.setPayType(orderPayDTO.getPayType());
		payGatewayDIO.setPayTargetChannelId(orderPayDTO.getPayTargetChannelId());
		payGatewayDIO.setPayTargetWay(orderPayDTO.getPayTargetType());
		payGatewayDIO.setSummary(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setPayTitle(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		if (Objects.nonNull(orderPay)) {
			payGatewayDIO.setAmount(orderPay.getAmount());
		} else {
			payGatewayDIO.setAmount(orderWork.getDepositAmount());
		}
		payGatewayDIO.setSyncResponse((orderPayDTO.getSyncFlag() == null || GlobalConsts.NO == orderPayDTO.getSyncFlag()) ? GlobalConsts.NO : GlobalConsts.YES);
		payGatewayDIO.setPayWayDIO(this.getPayWayDIO(orderPayDTO));
		payGatewayDIO.setTradeCategOneId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getOneId());
		payGatewayDIO.setTradeCategTwoId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getTwoId());
		payGatewayDIO.setTradeCategThreeId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getThirdId());
		payGatewayDIO.setAppId(AppEnum.APP_OMS.getAppId());
		payGatewayDIO.setAppName(AppEnum.getAppNameByAppId(AppEnum.APP_OMS.getAppId()));
		payGatewayDIO.setAppBizNo(String.valueOf(orderPayDTO.getOrderId()));
		String subBizNo = String.format("%s%s%s%s%s-%s", PayAmountTypeConsts.ORDER_IN_DEPOSIT, orderPayDTO.getPayChannelId(),
				orderPayDTO.getPayType(), Optional.ofNullable(orderPayDTO.getPayTargetChannelId()).orElse(0),count,
				StringUtils.defaultIfBlank(orderPayDTO.getOpenId(), "")
		);
		payGatewayDIO.setAppSubBizNo(subBizNo);
		payGatewayDIO.setNoticMqTopic(OMS_MQ_TOPIC);
		payGatewayDIO.setNoticeMqTag(MessageQueueTagConsts.OMS_ORDERPAY);
		payGatewayDIO.setNoticeMqExtendData(JSON.toJSONString(omsPayRequestDTO));
		payGatewayDIO.setOperator(orderPayDTO.getOperator());
		payGatewayDIO.setOperatorId(orderPayDTO.getOperatorId());
		payGatewayDIO.setOperatorType(orderPayDTO.getOperatorType());
		payGatewayDIO.setOperatorRemark(orderPayDTO.getOperatorRemark());

		// 支付宝支付 传产品信息过去
		if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_ALIPAY)) {
			AlipayGoodsDetailDIO goodsDetailDIO = new AlipayGoodsDetailDIO();
			goodsDetailDIO.setGoodsId(String.valueOf(orderWork.getShowProductId()));
			goodsDetailDIO.setPrice(payGatewayDIO.getAmount());
			goodsDetailDIO.setGoodsName(orderDetail.getProductInfo());
			goodsDetailDIO.setQuantity(1);
			payGatewayDIO.setAlipayGoodsDetails(Lists.newArrayList(goodsDetailDIO));
		}

		log.info("{} payDepositAmount 支付入参：{}", orderId, JSON.toJSONString(payGatewayDIO));
		ResponseDTO<PayGatewayDRO> responseDTO = payGatewayRemoteService.pay(payGatewayDIO);
		log.info("{} payDepositAmount 支付出参：{}", orderId, JSON.toJSONString(responseDTO));
		if (!responseDTO.isSuccess()) {
			throw new OmsBaseException(responseDTO.getMessage());
		}

		return responseDTO.getData();
	}

	/**
	 * 支付进度款
	 *
	 * @param orderPayDTO
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	public PayGatewayDRO progressPayAmount(ZsOrderPayDTO orderPayDTO) throws OmsBaseException {
		Long orderId = orderPayDTO.getOrderId();
		Long workId = orderPayDTO.getWorkId();
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);

		if (orderWork == null) {
			throw new OmsBaseException("工单不存在");
		}
		if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
			throw new OmsBaseException("订单已取消");
		}
		if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_COMPLETE) {
			throw new OmsBaseException("订单已完结");
		}

		// 获取微信临时二维码（通过模版消息支付）
		if (this.needWechatQrCode(orderWork, orderWork.getPlatWork(), orderPayDTO.getPayChannelId(), orderPayDTO.getPayType())) {
			String qrCode = this.getWechatQrcode(orderId, WechatQrConststs.QR_TYPE_MASTER_DEPOSIT_AMOUNT_PAY);
			log.info("定金模版消息支付==>platWork:{},payChannelId:{},payType:{},qrCode:{}",
					orderWork.getPlatWork(), orderPayDTO.getPayChannelId(), orderPayDTO.getPayType(), qrCode);
//			String qrCode = this.getWechatQrcode(orderPayDTO.getOrderId(), "TempDepositPay", orderPayDTO.getOperator());
			if (StringUtils.isNotBlank(qrCode)) {
				PayGatewayDRO payGatewayDRO = new PayGatewayDRO();
				payGatewayDRO.setQrCode(qrCode);
				return payGatewayDRO;
			}
		}

		// 待支付不存在
		if (NumberUtil.isNullOrZero(orderPayDTO.getOrderPayId())) {
			throw new OmsBaseException("待支付不存在");
		}
		OrderPay orderPay = orderPayService.findOrderPayByKeySrcMaster(orderWork.getOrderId(), orderPayDTO.getOrderPayId());
		if (Objects.isNull(orderPay)) {
			throw new OmsBaseException("当前支付已取消");
		}
		Integer count = orderPayService.countByOrderIdAndWorkIdSrcMaster(orderWork.getOrderId(), orderWork.getWorkId());

		// 附加请求数据，供支付后续业务处理
		OmsPayRequestDTO omsPayRequestDTO = new OmsPayRequestDTO();
		omsPayRequestDTO.setPlat(orderPayDTO.getPlat());
		omsPayRequestDTO.setAppPlat(orderPayDTO.getAppPlat());
		omsPayRequestDTO.setVersion(orderPayDTO.getVersion());
		omsPayRequestDTO.setDisplayVersion(orderPayDTO.getDisplayVersion());
		omsPayRequestDTO.setOrderId(orderId);
		omsPayRequestDTO.setWorkId(workId);
		omsPayRequestDTO.setAmountType(OrderPayConsts.ORDER_PAY_PROGRESS);
		omsPayRequestDTO.setAgentType(orderPayDTO.getAgentType());
		omsPayRequestDTO.setOperator(orderPayDTO.getOperator());
		omsPayRequestDTO.setOperatorId(orderPayDTO.getOperatorId());
		omsPayRequestDTO.setOperatorType(orderPayDTO.getOperatorType());
		omsPayRequestDTO.setLongitude(orderPayDTO.getLongitude());
		omsPayRequestDTO.setLatitude(orderPayDTO.getLatitude());
		omsPayRequestDTO.setAcceptanceId(orderPayDTO.getAcceptanceId());
		omsPayRequestDTO.setOrderPayId(orderPayDTO.getOrderPayId());
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

		PayGatewayDIO payGatewayDIO = new PayGatewayDIO();
		payGatewayDIO.setPlat(orderPayDTO.getPlat());
		payGatewayDIO.setPayPlat(orderPayDTO.getPlat());
		payGatewayDIO.setPayChannelId(orderPayDTO.getPayChannelId());
		payGatewayDIO.setPayType(orderPayDTO.getPayType());
		payGatewayDIO.setPayTargetChannelId(orderPayDTO.getPayTargetChannelId());
		payGatewayDIO.setPayTargetWay(orderPayDTO.getPayTargetType());
		payGatewayDIO.setSummary(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setPayTitle(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setAmount(orderPay.getAmount());
		payGatewayDIO.setSyncResponse((orderPayDTO.getSyncFlag() == null || GlobalConsts.NO == orderPayDTO.getSyncFlag()) ? GlobalConsts.NO : GlobalConsts.YES);
		payGatewayDIO.setPayWayDIO(this.getPayWayDIO(orderPayDTO));
		payGatewayDIO.setTradeCategOneId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getOneId());
		payGatewayDIO.setTradeCategTwoId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getTwoId());
		payGatewayDIO.setTradeCategThreeId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getThirdId());
		payGatewayDIO.setAppId(AppEnum.APP_OMS.getAppId());
		payGatewayDIO.setAppName(AppEnum.getAppNameByAppId(AppEnum.APP_OMS.getAppId()));
		payGatewayDIO.setAppBizNo(String.valueOf(orderPayDTO.getOrderId()));
		String subBizNo = String.format("%s%s%s%s%s-%s", OrderPayConsts.ORDER_PAY_PROGRESS, orderPayDTO.getPayChannelId(),
				orderPayDTO.getPayType(), Optional.ofNullable(orderPayDTO.getPayTargetChannelId()).orElse(0),count,
				StringUtils.defaultIfBlank(orderPayDTO.getOpenId(), "")
		);
		payGatewayDIO.setAppSubBizNo(subBizNo);
		payGatewayDIO.setNoticMqTopic(OMS_MQ_TOPIC);
		payGatewayDIO.setNoticeMqTag(MessageQueueTagConsts.OMS_ORDERPAY);
		payGatewayDIO.setNoticeMqExtendData(JSON.toJSONString(omsPayRequestDTO));
		payGatewayDIO.setOperator(orderPayDTO.getOperator());
		payGatewayDIO.setOperatorId(orderPayDTO.getOperatorId());
		payGatewayDIO.setOperatorType(orderPayDTO.getOperatorType());
		payGatewayDIO.setOperatorRemark(orderPayDTO.getOperatorRemark());

		// 支付宝支付 传产品信息过去
		if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_ALIPAY)) {
			AlipayGoodsDetailDIO goodsDetailDIO = new AlipayGoodsDetailDIO();
			goodsDetailDIO.setGoodsId(String.valueOf(orderWork.getShowProductId()));
			goodsDetailDIO.setPrice(payGatewayDIO.getAmount());
			goodsDetailDIO.setGoodsName(orderDetail.getProductInfo());
			goodsDetailDIO.setQuantity(1);
			payGatewayDIO.setAlipayGoodsDetails(Lists.newArrayList(goodsDetailDIO));
		}

		log.info("{} payDepositAmount 支付入参：{}", orderId, JSON.toJSONString(payGatewayDIO));
		ResponseDTO<PayGatewayDRO> responseDTO = payGatewayRemoteService.pay(payGatewayDIO);
		log.info("{} payDepositAmount 支付出参：{}", orderId, JSON.toJSONString(responseDTO));
		if (!responseDTO.isSuccess()) {
			throw new OmsBaseException(responseDTO.getMessage());
		}

		return responseDTO.getData();
	}

	/**
	 * 支付优惠金额
	 *
	 * @param orderWork
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	public PayGatewayDRO payDiscountAmount(OrderWork orderWork) {
		List<OrderDiscount> discountList = orderDiscountService.listByOrderId(orderWork.getOrderId());
		if (CollectionUtils.isEmpty(discountList)) {
			return null;
		}

		return this.payDiscountAmount(orderWork.getPlatWork(), orderWork.getOrderId(), orderWork.getWorkId(), GlobalConsts.NO, discountList);
	}

	/**
	 * 支付优惠金额
	 * @param plat
	 * @param orderId
	 * @param workId
	 * @param syncFlag
	 * @param discountList
	 * @return
	 */
	@Override
	public PayGatewayDRO payDiscountAmount(Integer plat, Long orderId, Long workId, Integer syncFlag, List<OrderDiscount> discountList) {
		if (CollectionUtils.isEmpty(discountList)) {
			return null;
		}

		Integer amountType = OrderPayConsts.ORDER_PAY_DISCOUNT; // 优惠券金额类型，兼容老fico
		int discountAmount = discountList.stream().mapToInt(e -> e.getAmount()).sum();
		OmsPayRequestDTO omsPayRequestDTO = new OmsPayRequestDTO();
		omsPayRequestDTO.setOrderId(orderId);
		omsPayRequestDTO.setWorkId(workId);
		omsPayRequestDTO.setAmountType(amountType);
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);
		PayGatewayDIO payGatewayDIO = new PayGatewayDIO();
		payGatewayDIO.setPlat(plat);
		payGatewayDIO.setPayPlat(plat);
		payGatewayDIO.setPayChannelId(PayConsts.PAY_CHANNEL_PLATFORM_DISCOUNT);
		payGatewayDIO.setPayType(PayConsts.PAY_TYPE_INTO);
		payGatewayDIO.setSummary(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setPayTitle(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setAmount(discountAmount);
		payGatewayDIO.setTradeCategOneId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getOneId());
		payGatewayDIO.setTradeCategTwoId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getTwoId());
		payGatewayDIO.setTradeCategThreeId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getThirdId());
		payGatewayDIO.setAppId(AppEnum.APP_OMS.getAppId());
		payGatewayDIO.setAppName(AppEnum.getAppNameByAppId(AppEnum.APP_OMS.getAppId()));
		payGatewayDIO.setAppBizNo(String.valueOf(orderId));
		String subBizNo = String.format("%s%s%s", amountType, PayConsts.PAY_CHANNEL_PLATFORM_DISCOUNT, PayConsts.PAY_TYPE_INTO);
		payGatewayDIO.setAppSubBizNo(subBizNo);
		payGatewayDIO.setNoticMqTopic(OMS_MQ_TOPIC);
		payGatewayDIO.setNoticeMqTag(MessageQueueTagConsts.OMS_ORDERPAY);
		payGatewayDIO.setNoticeMqExtendData(JSON.toJSONString(omsPayRequestDTO));
		payGatewayDIO.setOperator("系统");
		payGatewayDIO.setOperatorId(1L);
		payGatewayDIO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_STAFF);
		log.info("{} payDiscountAmount 支付入参：{}", orderId, JSON.toJSONString(payGatewayDIO));
		ResponseDTO<PayGatewayDRO> responseDTO = payGatewayRemoteService.pay(payGatewayDIO);
		log.info("{} payDiscountAmount 支付入参：{}", orderId, JSON.toJSONString(responseDTO));
		if (responseDTO.isSuccess()) {
			return responseDTO.getData();
		} else {
			log.error("{}优惠券支付失败{}", discountList, payGatewayDIO);
			return null;
		}
	}

	/**
	 * 支付渠道预付(同步支付)
	 *
	 * @param orderWork
	 * @return
	 * @throws OmsBaseException
	 */
	@Override
	public PayGatewayDRO payChannelPrepaidAmount(OrderWork orderWork) throws OmsBaseException {
		if (orderWork.getChannelPrepayAmount() == null || orderWork.getChannelPrepayAmount() <= 0) {
			return null;
		}

		// 附加请求数据，供支付后续业务处理
		OmsPayRequestDTO omsPayRequestDTO = new OmsPayRequestDTO();
		omsPayRequestDTO.setOrderId(orderWork.getOrderId());
		omsPayRequestDTO.setWorkId(orderWork.getWorkId());
		omsPayRequestDTO.setAmountType(PayAmountTypeConsts.ORDER_IN_CHANNEL_PREPAY);
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderWork.getOrderId());

		PayGatewayDIO payGatewayDIO = new PayGatewayDIO();
		payGatewayDIO.setPlat(orderWork.getPlatWork());
		payGatewayDIO.setPayPlat(orderWork.getPlatWork());
		payGatewayDIO.setPayChannelId(PayConsts.PAY_CHANNEL_PLATFORM_CHANNEL);
		payGatewayDIO.setIdentityObjectId((long)orderWork.getChannelId());
		payGatewayDIO.setPayType(PayConsts.PAY_TYPE_INTO);
		payGatewayDIO.setSummary(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setPayTitle(ProductInfoUtil.getProductName(orderDetail.getProductInfo()));
		payGatewayDIO.setAmount(orderWork.getChannelPrepayAmount());
		payGatewayDIO.setTradeCategOneId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getOneId());
		payGatewayDIO.setTradeCategTwoId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getTwoId());
		payGatewayDIO.setTradeCategThreeId(OrderTypeConsts.AccountTradeCategEnum.CONSUME_ORDER_PAY.getThirdId());
		payGatewayDIO.setAppId(AppEnum.APP_OMS.getAppId());
		payGatewayDIO.setAppName(AppEnum.getAppNameByAppId(AppEnum.APP_OMS.getAppId()));
		payGatewayDIO.setAppBizNo(String.valueOf(orderWork.getOrderId()));
		String subBizNo = String.format("%s%s%s", PayAmountTypeConsts.ORDER_IN_CHANNEL_PREPAY, PayConsts.PAY_CHANNEL_PLATFORM_CHANNEL, PayConsts.PAY_TYPE_INTO);
		payGatewayDIO.setAppSubBizNo(subBizNo);
		payGatewayDIO.setNoticMqTopic(OMS_MQ_TOPIC);
		payGatewayDIO.setNoticeMqTag(MessageQueueTagConsts.OMS_ORDERPAY);
		payGatewayDIO.setNoticeMqExtendData(JSON.toJSONString(omsPayRequestDTO));
		payGatewayDIO.setOperator("系统");
		payGatewayDIO.setOperatorId(1L);
		payGatewayDIO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_STAFF);
		log.info("{} payChannelPrepaidAmount 支付入参：{}", orderWork.getOrderId(), JSON.toJSONString(payGatewayDIO));
		ResponseDTO<PayGatewayDRO> responseDTO = payGatewayRemoteService.pay(payGatewayDIO);
		log.info("{} payChannelPrepaidAmount 支付入参：{}", orderWork.getOrderId(), JSON.toJSONString(responseDTO));
		if (responseDTO.isSuccess()) {
			return responseDTO.getData();
		} else {
			throw new OmsBaseException(responseDTO.getMessage());
		}
	}

	/**
	 * 保存厂商资金帐号退款结果
	 */
	private void saveFactoryRefundResult(RefundInitiateBO refundInitiateBO) {
		OrderWork refundOrderWork = refundInitiateBO.getRefundOrderWork();
		OmsOperator operator = refundInitiateBO.getOperator();

		OmsRefundRequestDTO omsRefundRequestDTO = new OmsRefundRequestDTO();
		omsRefundRequestDTO.setRefundType(refundInitiateBO.getRefundType());
		omsRefundRequestDTO.setRefundInitiateType(refundInitiateBO.getRefundInitiateType());
		omsRefundRequestDTO.setOrderId(refundOrderWork.getOrderId());
		omsRefundRequestDTO.setWorkId(refundOrderWork.getWorkId());
		omsRefundRequestDTO.setOperatorType(operator.getOperatorType());
		omsRefundRequestDTO.setOperatorId(operator.getOperatorId());
		omsRefundRequestDTO.setOperator(operator.getOperator());
		omsRefundRequestDTO.setOrderPayId(refundInitiateBO.getOrderPayId());
		List<OrderPay> orderPayList = orderPayBService.listOrderPayByOrderId(refundOrderWork.getOrderId());
		List<OrderPay> payOrders = orderPayList.stream().filter(e -> Objects.equals(e.getTradeType(), PayConsts.PAY_TRADE_TYPE_INTIME)).collect(Collectors.toList());
		Integer channelId;
		Integer payType;
		if (CollectionUtil.isNotNullOrEmpty(payOrders)) {
			channelId = payOrders.get(0).getPayChannelId();
			payType = payOrders.get(0).getPayType();
		} else {
			channelId = PayConsts.PAY_CHANNEL_PLATFORM_CREDIT;
			payType = PayConsts.PAY_TYPE_INTO;
		}
		RefundResultDRO refundResultDRO = new RefundResultDRO();
		refundResultDRO.setPlat(refundOrderWork.getPlatWork());
		refundResultDRO.setChannelId(channelId);
		refundResultDRO.setPayType(payType);
		refundResultDRO.setRefundInnerTradeNo("");
		refundResultDRO.setRefundOutTradeNo("");
		refundResultDRO.setStatus(PayConsts.REFUND_STATUS_DONE);
		refundResultDRO.setRefundAmount(refundInitiateBO.getRefundAmount());
		refundResultDRO.setRefundTime(new Date());
		refundResultDRO.setRequestData(JSON.toJSONString(omsRefundRequestDTO));
		if (!Objects.equals(refundInitiateBO.getRefundInitiateType(), RefundInitiateTypeEnum.REFUND_DIFFERENCE.getType())) {
			refundBService.updateNewRefundResult(refundResultDRO);
		}else {
			refundBService.differenceRefundCallback(refundResultDRO);
		}

	}

	/** @Author wangyanci
	 * @Description 支付退款金额
	 * @Date 15:17 2022/4/14
	 * @Param refundInitiateBO
	 * @return RefundDRO
	 **/
	@Override
	public RefundDRO payRefundAmount(RefundInitiateBO refundInitiateBO) throws OmsBaseException {
		// 厂商先操作资金账户退款
		if (Objects.equals(refundInitiateBO.getOriginalOrderWorkBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F)) {
			factoryAccountModifyBService.refund(refundInitiateBO);
			// 更新退款结果
			this.saveFactoryRefundResult(refundInitiateBO);
			return null;
		}

		if (NumberUtil.isNullOrZero(refundInitiateBO.getRefundAmount())) {
			return null;
		}

		OrderWork refundOrderWork = refundInitiateBO.getRefundOrderWork();
		OmsOperator operator = refundInitiateBO.getOperator();
		List<OrderPay> orderPayList = refundInitiateBO.getOrderPayList();
		// 如果不属于重复支付退款，则过滤掉重复支付的支付流水
		if (!Objects.equals(refundInitiateBO.getRefundInitiateType(), RefundInitiateTypeEnum.REFUND_DUPLICATE.getType())) {
			orderPayList = orderPayList.stream().filter(pay -> !Objects.equals(pay.getDuplicate(), GlobalConsts.YES))
					.collect(Collectors.toList());
		}

		// 获取支付流水
		Set<String> tradeNos = this.getPayRefundAmountTradeNos(refundInitiateBO);

		RefundGatewayDIO refundGatewayDIO = new RefundGatewayDIO();
		refundGatewayDIO.setOffLineRefund(Objects.equals(refundInitiateBO.getRefundType(), OrderConsts.ORDER_REFUND_TYPE_OFFLINE) ? GlobalConsts.YES : GlobalConsts.NO);
		refundGatewayDIO.setInnerPayTradeNos(tradeNos);
		refundGatewayDIO.setPlat(refundOrderWork.getPlatWork());
		refundGatewayDIO.setAmount(refundInitiateBO.getRefundAmount());
		if (Objects.equals(refundInitiateBO.getRefundType(), OrderConsts.ORDER_REFUND_TYPE_ONLINE)) {
			refundGatewayDIO.setTradeCategOneId(OrderTypeConsts.AccountTradeCategEnum.REFUND_CANCLE_ORDER.getOneId());
			refundGatewayDIO.setTradeCategTwoId(OrderTypeConsts.AccountTradeCategEnum.REFUND_CANCLE_ORDER.getTwoId());
			refundGatewayDIO.setTradeCategThreeId(OrderTypeConsts.AccountTradeCategEnum.REFUND_CANCLE_ORDER.getThirdId());
		} else {
			refundGatewayDIO.setTradeCategOneId(OrderTypeConsts.AccountTradeCategEnum.REFUND_MANUAL.getOneId());
			refundGatewayDIO.setTradeCategTwoId(OrderTypeConsts.AccountTradeCategEnum.REFUND_MANUAL.getTwoId());
			refundGatewayDIO.setTradeCategThreeId(OrderTypeConsts.AccountTradeCategEnum.REFUND_MANUAL.getThirdId());
		}
		refundGatewayDIO.setAppId(AppEnum.APP_OMS.getAppId());
		refundGatewayDIO.setAppName(AppEnum.getAppNameByAppId(AppEnum.APP_OMS.getAppId()));
		refundGatewayDIO.setAppBizNo(String.valueOf(refundOrderWork.getWorkId()));
		// 工程师收款类型
		String subBizNo = String.format("%s%s%s%s", GlobalConsts.NONE, PayConsts.PAY_CHANNEL_PLATFORM_OFFLINE, PayConsts.PAY_TYPE_MANUAL, DateUtil.getNowTimestamp());
		refundGatewayDIO.setAppSubBizNo(subBizNo);
		refundGatewayDIO.setNoticeMqTopic(OMS_MQ_TOPIC);
		refundGatewayDIO.setNoticeMqTag(RefundInitiateTypeEnum.getRefundNoticeMqTag(refundInitiateBO.getRefundInitiateType()));
		refundGatewayDIO.setRefundTargetChannelId(refundInitiateBO.getPayTargetChannelId());
		refundGatewayDIO.setRefundTargetWay(PayConsts.PAY_TYPE_MANUAL);
		refundGatewayDIO.setOperator(Optional.ofNullable(operator.getOperator()).orElse("系统"));
		refundGatewayDIO.setOperatorId(operator.getOperatorId());
		refundGatewayDIO.setOperatorType(operator.getOperatorType());
		refundGatewayDIO.setOperatorRemark(operator.getOperatorRemark());
		refundGatewayDIO.setRefundInstructions(operator.getOperatorRemark());
		if (StringUtils.isNotBlank(refundInitiateBO.getPayeeThirdAccount())) {
			Map map = new HashMap();
			map.put("payeeThirdAccount", refundInitiateBO.getPayeeThirdAccount());
			map.put("payeeThirdAccountName", refundInitiateBO.getPayeeThirdAccountName());
			map.put("payeeThirdAccountBank", refundInitiateBO.getPayeeThirdAccountBank());
			refundGatewayDIO.setRefundChannelData(JSON.toJSONString(map));
		}
		// 百度支付获取accessToken
		String accessToken = null;
		boolean includeBaiduPay = orderPayList.stream().anyMatch(e -> Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_BAIDU));
		if (includeBaiduPay) {
			ResponseDTO<String> getTokenRemote = appRemoteService.getAccessTokenByThirdAppId(baiduAppId);
			log.info("获取百度tokenappRemoteService.getAccessTokenByThirdAppId入参[{}]，出参[{}]", baiduAppId, JSON.toJSONString(getTokenRemote));
			if (getTokenRemote.isSuccess()) {
				accessToken = getTokenRemote.getData();
			}
		}
		// 快手支付获取accessToken
		boolean includeKuaishouPay = orderPayList.stream().anyMatch(e -> Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_KUAISHOU));
		if (includeKuaishouPay) {
			ResponseDTO<String> getTokenRemote = appRemoteService.getAccessTokenByThirdAppId(kaishouAppId);
			log.info("获取快手tokenappRemoteService.getAccessTokenByThirdAppId入参[{}]，出参[{}]", kaishouAppId, JSON.toJSONString(getTokenRemote));
			if (getTokenRemote.isSuccess()) {
				accessToken = getTokenRemote.getData();
			}
		}
		refundGatewayDIO.setAccessToken(accessToken);
		// 附加请求数据，供支付后续业务处理
		OmsRefundRequestDTO omsPayRequestDTO = new OmsRefundRequestDTO();
		omsPayRequestDTO.setOrderPayId(refundInitiateBO.getOrderPayId());
		omsPayRequestDTO.setPayTargetChannelId(refundInitiateBO.getPayTargetChannelId());
		omsPayRequestDTO.setOrderId(refundOrderWork.getOrderId());
		omsPayRequestDTO.setWorkId(refundOrderWork.getWorkId());
		omsPayRequestDTO.setRefundType(refundInitiateBO.getRefundType());
		omsPayRequestDTO.setRefundInitiateType(refundInitiateBO.getRefundInitiateType());
		refundGatewayDIO.setNoticeMqExtendData(JSON.toJSONString(omsPayRequestDTO));
		log.info("{} payRefundAmount 支付入参：{}", refundOrderWork.getWorkId(), JSON.toJSONString(refundGatewayDIO));
		ResponseDTO<List<RefundDRO>> listResponseDTO = refundRemoteService.refundNew(refundGatewayDIO);
		log.info("{} payRefundAmount 支付出参：{}", refundOrderWork.getWorkId(), JSON.toJSONString(listResponseDTO));
		if (listResponseDTO.isSuccess()) {
			return listResponseDTO.getData().get(0);
		} else {
			log.error("{}退款支付失败{}", refundOrderWork.getWorkId(), listResponseDTO.getMessage());
			throw new OmsBaseException(listResponseDTO.getMessage());
		}
	}


	/**
	 * 生成工单支付唯一id
	 *
	 * @param plat
	 * @param amountType
	 * @param payBizCode
	 * @param workId
	 * @return
	 */
	private String getPayUniqueId(Integer plat, Integer tradeType, Integer amountType, String payBizCode, Long workId) {
		return String.format("%s%s%s%s%s", plat, tradeType, amountType, payBizCode, workId);
	}

	/**
	 * 获取微信临时二维码（通过模版消息支付）
	 * @param orderId
	 * @param qrCodeType
	 * @return
	 */
	@Override
	public String getWechatQrcode(Long orderId,String qrCodeType,String operator) {
		Map<String, String> params = Maps.newHashMap();
		params.put("orderId", String.valueOf(orderId));
		params.put("qrCodeType", qrCodeType);
		params.put("operator", operator);
		try {
			String response = HttpUtil.post(WECHAT_QRCODE_URL, params);
			if (StringUtils.isNotBlank(response)) {
				JSONObject jsonObject = JSON.parseObject(response);
				if (jsonObject != null && "1".equals(jsonObject.getString("status"))) {
					return jsonObject.getString("qrCode");
				}
			}
		} catch (Exception e) {
			log.error("获取微信临时二维码失败",e);
		}

		return null;
	}

	@Override
	public String getWechatQrcode(Long orderId, Integer qrCodeType) {

		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
		if (orderWork == null) {
			log.error("#oms#getWechatQrcode#{} 订单为空", orderId);
			return "";
		}

		// topic
		String topicOms = MqTopicConsts.ZMN_TOPIC_OMS;
		// topic tag
		String topicOmsTag = OmsMqTagConsts.ZMN_TOPIC_OMS_WECHAT_SCAN_QR;
		// 业务Id
		Long businessId = orderId;
		// 业务类型
		Integer businessType = qrCodeType;
		// userId
		Long userId = orderWork.getUserId();
		Integer cityId = orderWork.getCityId();
		Integer platWork = orderWork.getPlatWork();
		OrderThirdAppBind orderThirdAppBind = messageGetSendInfoService.getOrderWeChatBindInfoForOrderBy(orderId, platWork);
		if (Objects.isNull(orderThirdAppBind)) {
			log.info("获取二维码失败，订单{}未绑定公众号 ===========", orderId);
			return "http://xiujiadian.com";
		}

		// 获取下单用户手机号码
		String mobile = messageGetSendInfoService.getUserMobileByUserId(orderId, userId);
		WeChatTemporaryQRCodeDIO dio = new WeChatTemporaryQRCodeDIO();
		dio.setUserId(userId);
		dio.setTopic(topicOms);
		dio.setTopicTag(topicOmsTag);
//		dio.setshopId(orderThirdAppBind.getAppShopId()); 取消了？
		dio.setChannelId(orderWork.getChannelId());
		dio.setType(businessType);
		dio.setCityId(cityId);
		dio.setTypeObjectId(String.valueOf(businessId));
		dio.setThirdAppId(orderThirdAppBind.getThirdAppId());
		dio.setMobile(mobile);

		log.info("#oms#订单号{},获取二维码入参：{}", orderWork.getOrderId(), JSON.toJSONString(dio));
		ResponseDTO<WeChatTemporaryQRCodeDRO> responseDTO = null;
		try {
			responseDTO = wechatTemporaryQrcodeModifyRemoteService.createQRCode(dio);

			// 新增日志 便于排查问题
			Long userIdLog = Optional.ofNullable(userId).orElse(0L);
			OrderMessageLog orderMessageLog = new OrderMessageLog();
			orderMessageLog.setOrderId(orderId + 300);// 区分其他节点日志
			orderMessageLog.setSendUserId(userIdLog);
			orderMessageLog.setGroupId(businessType);
			orderMessageLog.setTagName(WechatQrConststs.getQrCodeTypeName(businessType));
			orderMessageLog.setContentIn(JSON.toJSONString(dio));
			orderMessageLog.setContentOut(JSON.toJSONString(responseDTO));
			orderMessageLog.setCreateTime(new Date());
			orderLogMessageBService.save(orderMessageLog);

		} catch (Exception e) {
			log.error("异常:" + e.getMessage(), e);
			return "http://xiujiadian.com";
		}
		log.info("#oms#订单号{},获取二维码出参：{}", orderWork.getOrderId(), JSON.toJSONString(responseDTO));

		if (!responseDTO.isSuccess()) {
			log.error("#oms#订单号{},获取二维码错误 {}", orderWork.getOrderId(), responseDTO.getMessage());
			return "http://xiujiadian.com";
		}

		return responseDTO.getData().getUrl();
	}

	@Override
	public String getWechatQrcode(OrderWork orderWork, Integer qrCodeType) {

		// topic
		String topicOms = MqTopicConsts.ZMN_TOPIC_OMS;
		// topic tag
		String topicOmsTag = OmsMqTagConsts.ZMN_TOPIC_OMS_WECHAT_SCAN_QR;
		// 业务Id
		Long businessId = orderWork.getOrderId();
		// 业务类型
		Integer businessType = qrCodeType;
		// userId
		Long userId = orderWork.getUserId();
		Integer cityId = orderWork.getCityId();
		Integer platWork = orderWork.getPlatWork();
		OrderThirdAppBind orderThirdAppBind = messageGetSendInfoService.getOrderWeChatBindInfoForOrderBy(orderWork.getOrderId(), platWork);
		if (Objects.isNull(orderThirdAppBind)) {
			log.info("获取二维码失败，订单{}未绑定公众号 ===========", orderWork.getOrderId());
			return "http://xiujiadian.com";
		}

		// 获取下单用户手机号码
		String mobile = messageGetSendInfoService.getUserMobileByUserId(orderWork.getOrderId(), userId);

		WeChatTemporaryQRCodeDIO dio = new WeChatTemporaryQRCodeDIO();
		dio.setUserId(userId);
		dio.setTopic(topicOms);
		dio.setTopicTag(topicOmsTag);
//		dio.setshopId(orderThirdAppBind.getAppShopId()); 取消了？
		dio.setChannelId(orderWork.getChannelId());
		dio.setType(businessType);
		dio.setCityId(cityId);
		dio.setTypeObjectId(String.valueOf(businessId));
		dio.setThirdAppId(orderThirdAppBind.getThirdAppId());
		dio.setMobile(mobile);

		log.info("#oms#订单号{},获取二维码入参：{}", orderWork.getOrderId(), JSON.toJSONString(dio));
		ResponseDTO<WeChatTemporaryQRCodeDRO> responseDTO = null;
		try {
			responseDTO = wechatTemporaryQrcodeModifyRemoteService.createQRCode(dio);

			// 新增日志 便于排查问题
			Long userIdLog = Optional.ofNullable(userId).orElse(0L);
			OrderMessageLog orderMessageLog = new OrderMessageLog();
			orderMessageLog.setOrderId(orderWork.getOrderId() + 300);// 区分其他节点日志
			orderMessageLog.setSendUserId(userIdLog);
			orderMessageLog.setGroupId(businessType);
			orderMessageLog.setTagName(WechatQrConststs.getQrCodeTypeName(businessType));
			orderMessageLog.setContentIn(JSON.toJSONString(dio));
			orderMessageLog.setContentOut(JSON.toJSONString(responseDTO));
			orderMessageLog.setCreateTime(new Date());
			orderLogMessageBService.save(orderMessageLog);

		} catch (Exception e) {
			log.error("异常:" + e.getMessage(), e);
			return "http://xiujiadian.com";
		}
		log.info("#oms#订单号{},获取二维码出参：{}", orderWork.getOrderId(), JSON.toJSONString(responseDTO));

		if (!responseDTO.isSuccess()) {
			log.error("#oms#订单号{},获取二维码错误 {}", orderWork.getOrderId(), responseDTO.getMessage());
			return "http://xiujiadian.com";
		}

		return responseDTO.getData().getUrl();
	}


	/**
	 * 是否需要生成公众号二维码
	 *
	 * @param plat
	 * @param payChannelId
	 * @param payType
	 * @return
	 */
	public boolean needWechatQrCode(OrderWork orderWork, Integer plat, Integer payChannelId, Integer payType) {
		// 除啄木鸟外其他平台没公众号的服务
		if (!Objects.equals(plat, GlobalConsts.PLAT_MARK_ZMN)) {
			return false;
		}
		if (!Objects.equals(PayConsts.PAY_TYPE_QR, payType)) {
			return false;
		}
		// 供应链支付主体-不支持
		Integer payPlat = this.getPayPlat(plat, payChannelId, orderWork.getServProductGroupId());
		if (Objects.equals(payPlat, PayConsts.PLAT_BN_SUPPLY)) {
			return false;
		}
		// 获取订单的绑定的appId
		String thirdAppId = messageGetSendInfoService.getOrderWeChatThirdAppId(orderWork.getOrderId(), plat);
		String activeProfile = this.getActiveProfile();
		// 生产环境
		if (Objects.equals(activeProfile, "prod") && !Objects.equals("wxecc02bbd01ef95d9", thirdAppId)) {
			return false;
		}

		if ("prod".equals(activeProfile) || "test".equals(activeProfile)) {
			if (Objects.equals(GlobalConsts.PAY_CHANNEL_PLATFORM_WEIXINPAY, payChannelId) && Objects.equals(GlobalConsts.PAY_TYPE_QR, payType)) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 是否需要支付宝小程序二维码
	 * @param plat
	 * @param payChannelId
	 * @param payType
	 * @return
	 */
	public boolean needAliXiaoChengXuQrCode(Integer plat, Integer payChannelId, Integer payType) {
		// 非啄木鸟平台不支持小程序付款工程师收款
		if (!Objects.equals(plat, GlobalConsts.PLAT_MARK_ZMN)) {
			return false;
		}
		if (!Objects.equals(PayConsts.PAY_CHANNEL_PLATFORM_ALIPAY, payChannelId)) {
			return false;
		}
		if (!Objects.equals(PayConsts.PAY_TYPE_QR, payType)) {
			return false;
		}

		// 是否支付小程序付工程师收款
		TagsQuery tagsDIO = new TagsQuery();
		tagsDIO.setPlat(plat);
		tagsDIO.setOneTypeId(TagConsts.TAG_ONE_TYPE_ALIXCX_SUPPORT_MASTERAMOUNT);
		ResponseDTO<List<TagsDRO>> codeMapRemote = tagsListRemoteService.listByTagsDIO(tagsDIO);

		boolean canpay = codeMapRemote.isSuccess() && (codeMapRemote.getData() != null && codeMapRemote.getData().stream().anyMatch(e -> Objects.equals(e.getStatus(), GlobalConsts.YES)));
		return canpay;
	}

	/**
	 * 获取支付标识
	 *
	 * @param orderWork
	 * @return
	 * 0 不需要支付，1 需要支付，2 已支付（已完成）,3 提示支付
	 */
	@Override
	public int getPayFlag(OrderWork orderWork) {

		// 工单已完成-返回已支付
		if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_COMPLETE) {
			return AppConsts.ORDER_PAY_FLAG_PAID;
		}

		// 保内单-返回不需要支付
		if (Objects.equals(com.zmn.consts.GlobalConsts.BIZ_TYPE_F, orderWork.getBizType())) {
			return AppConsts.ORDER_PAY_FLAG_NONE;
		}

		// 工程师收款为0或支付状态为已支付，返回不需要支付
		if (Objects.equals(0, orderWork.getMasterAmount()) || Objects.equals(orderWork.getPayStatus(), PayConsts.PAY_STATUS_DONE)) {
			return AppConsts.ORDER_PAY_FLAG_NONE;
		}

		// 渠道支付---返回渠道支付标识
		List<PayChannelDRO> listPayChannel = orderPayChannelBService.listPayChannel(orderWork.getPlatWork(), orderWork.getBizModeSource(), orderWork.getChannelId(), orderWork.getServProductGroupId());
		boolean isThirdPay = listPayChannel.stream()
				.anyMatch(e -> Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_CHANNEL));
		if (isThirdPay) {
			return AppConsts.APP_PAY_FLAG_THIRD_PAY;
		}

		// 如果没有上门用户，查询微信扫码用户是否存在
		if (NumberUtil.isNullOrZero(orderWork.getVisitUserId())) {
			OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderWork.getOrderId());
			if (Objects.isNull(orderExtend) || NumberUtil.isNullOrZero(orderExtend.getWeChatScanUserId())) {
				return AppConsts.ORDER_PAY_FLAG_UNPAID;
			}
			orderWork.setVisitUserId(orderExtend.getWeChatScanUserId());
		}

		// 是否需要用户支付
		Boolean needUserPay = false;
		if (!ProductConsts.LIST_SPECIAL_SERV_PRODUCT_GROUP.contains(orderWork.getServProductGroupId()) &&
				Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_ZMN) && NumberUtil.isNotNullOrZero(orderWork.getVisitUserId())) {
			log.info("{}支持用户模版消息支付", orderWork.getWorkId());
			boolean eciticPay = listPayChannel.stream()
					.anyMatch(e -> Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_THIRD_ECITIC));
			boolean weixinPay = listPayChannel.stream()
					.anyMatch(e -> Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_WEIXINPAY));
			if (eciticPay || weixinPay) {
				needUserPay = true;// 支持中信或微信支付，才给用户支付
			}
		}

		if (needUserPay) {
			// 发送消息
			boolean result = false;
			try {
				result = masterWorkBService.sendWaitPayNotice(orderWork.getOrderId(), orderWork.getWorkId(), 2);
			} catch (OmsBaseException e) {

			}
			return result ? AppConsts.APP_PAY_FLAG_VISIT_USER : AppConsts.APP_PAY_FLAG_VISIT_USER_FALSE;
		} else {
			return AppConsts.ORDER_PAY_FLAG_UNPAID;
		}
	}

	/**
	 * 获取当前环境参数  exp: dev,prod,test
	 *
	 * @return
	 */
	private String getActiveProfile() {
		String[] profiles = SpringBeanFactoryUtil.getApplicationContext().getEnvironment().getActiveProfiles();
		if (!ArrayUtils.isEmpty(profiles)) {
			return profiles[0];
		}
		return "";
	}

	/**
	 * 获取支付平台
	 *
	 * @param platWork
	 * @param servProductGroupId
	 * @return
	 */
	private Integer getPayPlat(Integer platWork, Integer payChannelId, Integer servProductGroupId) {
		// 特殊产品分组，支付到供应链公司
		if (ProductConsts.LIST_SPECIAL_SERV_PRODUCT_GROUP.contains(servProductGroupId)) {
			return 50; //TODO 常量待替换
		}

		// 银联支付，付到只能啄木鸟公司
		if (Objects.equals(payChannelId, PayConsts.PAY_CHANNEL_THIRD_ECITIC)) {
			return GlobalConsts.PLAT_MARK_ZMN;
		}
		return platWork;
	}

    /**
     * 获取师傅电话
     *
     * @param orderId
     * @param workId
     * @return
     */
    private String getMasterPhone(Long orderId, Long workId) {
        // 查询订单工程师列表
        List<OrderMaster> masterList = orderMasterService.listMasterByWorkId(orderId, workId, OrderConsts.ORDER_MASTER_TYPE_MAIN);
        if (!CollectionUtils.isEmpty(masterList)) {
            return masterList.get(0).getMasterPhone();
        }
        return null;
    }

	/**
	 * 缓存支付二维码链接
	 * @param orderId
	 * @param payUrl
	 */
	private void cachePayUrl(Long orderId, String payUrl) {
		if (orderId == null || StringUtils.isBlank(payUrl)) {
			return;
		}
		try {
			String redisKey = String.format(RedisKeyConsts.CHANNEL_PAY_QRCODE_ID, String.valueOf(orderId));
			redisManager.setex(redisKey, payUrl, RedisKeyConsts.CHANNEL_PAY_QRCODE_ID_EXPIRE_SECONDS);
		} catch (Exception e) {
			log.error(String.format("OrderId=[%s]: 缓存支付二维码失败：%s, payUrl=[%s]",
					String.valueOf(orderId), e.getMessage(), payUrl), e);
		}
	}

	/**
	 * 获取缓存的支付二维码链接，没有则返回null
	 * @param orderId
	 * @return
	 */
    private String getCachedPayUrl(Long orderId) {
    	if (orderId == null) {
    		return null;
		}
		try {
			String redisKey = String.format(RedisKeyConsts.CHANNEL_PAY_QRCODE_ID, String.valueOf(orderId));
			String payUrl = redisManager.get(redisKey);
			return StringUtils.isNotBlank(payUrl) ? payUrl : null;
		} catch (Exception e) {
			log.error(String.format("OrderId=[%s]: 获取缓存支付二维码失败：%s",
					String.valueOf(orderId), e.getMessage()), e);
		}
		return null;
	}

	/**
	 * 缓存支付二维码链接
	 * @param orderId
	 * @param payLinkInfo
	 */
	private void cachePayLinkInfo(Long orderId, PayLinkInfo payLinkInfo) {
		if (orderId == null || payLinkInfo == null || StringUtils.isBlank(payLinkInfo.getPayLink())) {
			return;
		}

		String value = JSON.toJSONString(payLinkInfo);
		try {
			String redisKey = String.format(RedisKeyConsts.CHANNEL_PAY_LINK_INFO, String.valueOf(orderId));
			redisManager.setex(redisKey, value, RedisKeyConsts.CHANNEL_PAY_QRCODE_ID_EXPIRE_SECONDS);
		} catch (Exception e) {
			log.error(String.format(
					"OrderId=[%s]: 缓存支付二维码失败：%s, payLinkInfo=[%s]",
					String.valueOf(orderId),
					e.getMessage(),
					value
			), e);
		}
	}

    /**
     * 缓存支付二维码链接
     * @param orderId       订单金额
     * @param payLinkInfo   支付链接信息
     * @param masterAmount  师傅收款金额
     */
    private void cachePayLinkInfo(Long orderId, PayLinkInfo payLinkInfo, Integer masterAmount) {
        if (orderId == null || payLinkInfo == null || masterAmount == null
                || StringUtils.isBlank(payLinkInfo.getPayLink())) {
            return;
        }

		StringJoiner replaceJoiner = new StringJoiner(".");
		replaceJoiner.add(String.valueOf(orderId));
		replaceJoiner.add(String.valueOf(masterAmount));
        String value = JSON.toJSONString(payLinkInfo);
        try {
            String redisKey = String.format(RedisKeyConsts.CHANNEL_PAY_LINK_INFO, replaceJoiner.toString());
            redisManager.setex(redisKey, value, RedisKeyConsts.CHANNEL_PAY_QRCODE_ID_EXPIRE_SECONDS);
        } catch (Exception e) {
            log.error(String.format(
                    "OrderId=[%s]: 缓存支付二维码失败：%s, payLinkInfo=[%s]",
                    String.valueOf(orderId),
                    e.getMessage(),
                    value
            ), e);
        }
    }

	/**
	 * 获取缓存的支付二维码链接，没有则返回null
	 * @param orderId
	 * @return
	 */
    private PayLinkInfo getCachedPayLinkInfo(Long orderId) {
    	if (orderId == null) {
    		return null;
		}
		try {
			String redisKey = String.format(RedisKeyConsts.CHANNEL_PAY_LINK_INFO, String.valueOf(orderId));
			String value = redisManager.get(redisKey);

			if (StringUtils.isBlank(value)) {
				return null;
			}

			PayLinkInfo payLinkInfo = JSON.parseObject(value, PayLinkInfo.class);

			return payLinkInfo;
		} catch (Exception e) {
			log.error(String.format("OrderId=[%s]: 获取缓存支付二维码失败：%s",
					String.valueOf(orderId), e.getMessage()), e);
		}
		return null;
	}

	/**
	 * 获取缓存的支付二维码链接，没有则返回null
	 * @param orderId       订单ID
	 * @param masterAmount  师傅收款金额
	 * @return
	 */
	private PayLinkInfo getCachedPayLinkInfo(Long orderId, Integer masterAmount) {
		if (orderId == null || masterAmount == null) {
			return null;
		}
		try {
            StringJoiner replaceJoiner = new StringJoiner(".");
            replaceJoiner.add(String.valueOf(orderId));
            replaceJoiner.add(String.valueOf(masterAmount));
			String redisKey = String.format(RedisKeyConsts.CHANNEL_PAY_LINK_INFO, replaceJoiner.toString());
			String value = redisManager.get(redisKey);

			if (StringUtils.isBlank(value)) {
				return null;
			}

			PayLinkInfo payLinkInfo = JSON.parseObject(value, PayLinkInfo.class);

			return payLinkInfo;
		} catch (Exception e) {
			log.error(String.format("OrderId=[%s]: 获取缓存支付二维码失败：%s",
					String.valueOf(orderId), e.getMessage()), e);
		}
		return null;
	}

	/**
	 * 获取支付通道参数
	 * @param orderPayDTO
	 * @return
	 */
	private BasePayWayDIO getPayWayDIO(ZsOrderPayDTO orderPayDTO) {
		BasePayWayDIO payWayDIO = null;
		if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_ALIPAY)) {
			AliPayDIO aliPayDIO = new AliPayDIO();
			payWayDIO = aliPayDIO;
		} else if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_WEIXINPAY)) {
			WxPayDIO wxPayDIO = new WxPayDIO();
			wxPayDIO.setWeixinAppId(orderPayDTO.getWeixinAppId());
			wxPayDIO.setTerminalIp(orderPayDTO.getWeixinH5PayCreateIp());
			payWayDIO = wxPayDIO;
		} else if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_BAIDU)) {
			BaiduPayDIO baiduPayDIO = new BaiduPayDIO();
			// baiduPayDIO.setAccessToken(orderPayDTO.getAccessToken());
			payWayDIO = baiduPayDIO;
		} else if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_BANKTRANSFER)) {
			BankTransferPayDIO bankTransferPayDIO = new BankTransferPayDIO();
			payWayDIO = bankTransferPayDIO;
		} else if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_TOUTIAO)) {
			ToutiaoPayDIO toutiaoPayDIO = new ToutiaoPayDIO();
			payWayDIO = toutiaoPayDIO;
		} else if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_THIRD_ECITIC)) {
			ZxUnionPayDIO toutiaoPayDIO = new ZxUnionPayDIO();
			toutiaoPayDIO.setZxAppId(orderPayDTO.getWeixinAppId());
			payWayDIO = toutiaoPayDIO;
		}else if (Objects.equals(orderPayDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_KUAISHOU)) {
			KSPayWayDIO ksPayWayDIO = new KSPayWayDIO();
			ksPayWayDIO.setAccessToken(orderPayDTO.getAccessToken());
			payWayDIO = ksPayWayDIO;
		}
		if (payWayDIO != null) {
			payWayDIO.setOpenId(orderPayDTO.getOpenId());
			payWayDIO.setCallbackUrl(orderPayDTO.getH5PayReturnUrl());
		}
		return payWayDIO;
	}

	@Override
	public void compensateRefund(OrderPayResultDRO resultDRO) throws OmsBaseException {
		// 查询工单信息
		OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(resultDRO.getOrderId(), resultDRO.getWorkId());


		String redisKey = String.format(RedisKeyConsts.ORDER_CANCELED_REFUND_KEY, resultDRO.getOrderId());
		if (!Objects.equals(OrderStatusConsts.ORDER_STATUS_CANCEL, orderWork.getStatus()) || !redisManager.exists(redisKey)) {
			return;
		}

		OrderPay orderPay = BeanMapper.map(resultDRO, OrderPay.class);
		List<OrderPay> payList = Lists.newArrayList(orderPay);

		OmsOperator operator = new RefundDTO();
		operator.setOperatorPlat(orderWork.getPlatWork());
		operator.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
		operator.setOperatorId((long)GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
		operator.setOperator("系统");

		Integer refundType = null;
		if (Objects.equals(resultDRO.getAmountType().intValue(), OrderPayConsts.ORDER_PAY_CHANNEL_PREPAY)) {
			refundType = OrderConsts.ORDER_REFUND_TYPE_OFFLINE;
		} else {
			refundType = OrderConsts.ORDER_REFUND_TYPE_ONLINE;
		}

		RefundInitiateBO refundInitiateBO = RefundInitiateBO.builder()
				.refundInitiateType(RefundInitiateTypeEnum.REFUND_ORDER.getType())
				.refundAmount(resultDRO.getAmount())
				.refundType(refundType)
				.refundOrderWork(orderWork)
				.orderPayList(payList)
				.operator(operator)
				.build();

		this.payRefundAmount(refundInitiateBO);
	}


	public void timesCardRefund(OrderWork orderWork, RefundDTO refundDTO) throws OmsBaseException {
		// 查询已退多少金额
		// 已退金额
		Integer discountRefundAmount = refundDTO.getDiscountRefundAmount();

		if (NumberUtil.isNotNullOrZero(discountRefundAmount)) {
			// 调用次卡退款
			// 查询优惠券信息
			List<OrderDiscount> orderDiscountList = orderDiscountService.listByOrderId(orderWork.getOrderId());
			String coupCode = orderDiscountList.stream().filter(discount -> {
				return Objects.equals(discount.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_ONCECARD.getSubType());
			}).findFirst().get().getItemCode();
			this.timesCardRefund(orderWork.getOrderId(), orderWork.getWorkId(), coupCode, discountRefundAmount,
					refundDTO.getRefundType(), refundDTO);
		}
	}

	@Override
	public void timesCardRefund(Long orderId, Long workId, String timesCardCoupCode, Integer refundAmount, Integer refundType, OmsOperator operator) throws OmsBaseException {
		RefundTimesCardDIO refundTimesCardDIO = new RefundTimesCardDIO();
		refundTimesCardDIO.setCouponCode(timesCardCoupCode);
		refundTimesCardDIO.setOperator(operator.getOperator());
		refundTimesCardDIO.setOperatorId(operator.getOperatorId());
		refundTimesCardDIO.setOperatorType(operator.getOperatorType());
		refundTimesCardDIO.setOrderId(orderId);
		refundTimesCardDIO.setWorkId(workId);
		refundTimesCardDIO.setRefundAmount(refundAmount);

		// 退款方式写死原路返回
		refundTimesCardDIO.setRefundPayType(VasPayConsts.PAY_ORIGINAL_REFUND_TYPE);

		ResponseDTO<RefundTimesCardDRO> refundResponseDTO = vasOrderTimesCardModifyRemoteService.refundVasOrderTimesCard(refundTimesCardDIO);
		log.info("订单[{}]调用次卡退款： 入参：{}, 出参：{}", orderId, JSON.toJSONString(refundTimesCardDIO),  JSON.toJSONString(refundResponseDTO));
		if (!refundResponseDTO.isSuccess()) {
			log.error("{}次卡退款支付失败{}", workId, refundResponseDTO.getMessage());
			throw new OmsBaseException(refundResponseDTO.getMessage());
		}
	}

	/**
	 * 获取退款支付单的流水号退款
	 *
	 * @param refundInitiateBO        退款方式
	 * @return
	 */
	private Set<String> getPayRefundAmountTradeNos(RefundInitiateBO refundInitiateBO) throws OmsBaseException {
		List<OrderPay> orderPayList = refundInitiateBO.getOrderPayList();
		OmsOperator operator = refundInitiateBO.getOperator();
		OrderWork refundOrderWork = refundInitiateBO.getRefundOrderWork();
		OrderWork originalOrderWork = orderWorkService.findOrderWorkByKey(refundOrderWork.getOrderId(), refundOrderWork.getOrderId());

		// 不是工程师发起的翻修单退款且不是原路退
		if (!Objects.equals(operator.getOperatorType(), GlobalConsts.OPERATE_USER_TYPE_MASTER)
				&& Objects.equals(refundInitiateBO.getRefundType(), OrderConsts.ORDER_REFUND_TYPE_ONLINE)
				&& Objects.equals(refundInitiateBO.getRefundInitiateType(), RefundInitiateTypeEnum.REFUND_ORDER.getType())) {
			RefundBacktrackingAmountDRO backTracking = refundBService.getBackTracking(originalOrderWork.getOrderId(), originalOrderWork.getDiscountPrepayAmount(), orderPayList);
			if (backTracking.isSupportBacktracking()) {
				return new HashSet<>(backTracking.getInnerTradeNoList());
			}
			return Sets.newHashSet();
		}
		return orderPayList.stream()
				.filter(pay -> StringUtil.isNotBlank(pay.getInnerTradeNo())
						&& Objects.equals(pay.getTradeType(), PayConsts.PAY_TRADE_TYPE_INTIME)
						&& !Objects.equals(pay.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_DISCOUNT))
				.map(OrderPay::getInnerTradeNo)
				.collect(Collectors.toSet());
	}

	/**
	 * 支付链接信息
	 */
	@Data
	public static class PayLinkInfo {
		private String payLink;
		private String channelPayTypeMsg;
	}
}
